Javascript 在节点中设置基于文件系统的路由
我非常喜欢PHP在页面服务中提供的简单性,一切都是基于文件系统的。我想对Node做同样的事情。我尝试了一种视图路由设置,但破坏了我的公用文件夹:Javascript 在节点中设置基于文件系统的路由,javascript,node.js,url-routing,Javascript,Node.js,Url Routing,我非常喜欢PHP在页面服务中提供的简单性,一切都是基于文件系统的。我想对Node做同样的事情。我尝试了一种视图路由设置,但破坏了我的公用文件夹: //using express: app.get('*', function(req, res) { file = req.params[0].substr(1, req.params[0].length); console.log('requesting: ' + file); res.render(file, {locals: {
//using express:
app.get('*', function(req, res) {
file = req.params[0].substr(1, req.params[0].length);
console.log('requesting: ' + file);
res.render(file, {locals: {
req: req,
params: req.query
}});
});
那么…在节点中设置基于文件系统/php样式的路由的最佳方法是什么呢?您可以使用express.static()
例如:
app.configure(function(){
app.use(express.static(__dirname + '/public'));
});
app.configure(function(){
app.use('/uploads', express.static(PATH_TO_UPLOAD_FOLDER));
});
我想我建造的正是你想要的。我用它来提供
.jade
文件,显然您可以根据您的用例调整它
var url = require('url');
var express = require('express');
var app = express.createServer();
var fs = require('fs');
app.set("view engine", "jade");
app.use(app.router);
app.use(express.static(__dirname + '/public'));
/**
* Generic "get" attempts to route to known JADE files.
* If no known JADE files, then we pass routing to next() (should be static).
*/
app.get('*', function(req, res, next) {
var pathname = url.parse(req.url).pathname.toLowerCase(); // make matching case insenstive
// First case: with no path name, render the default index.jade
if(!pathname) {
res.render('index', {});
}
// Second case: path ending in '/' points to a folder, use index.jade from that folder
else if (pathname === '/' || pathname.charAt(pathname.length-1) === '/' ){
res.render(__dirname + '/views' + pathname + 'index.jade', {});
}
// Third case: looks like an actual file, attempt to render
else {
// Attempt to find the referenced jade file and render that. Note 'views' is default path.
fs.stat( (__dirname + "/views" + pathname + '.jade'), function(err, stats){
// There was an error, the file does not exist pass control to the static handler
if(err || !stats) {
next();
}
// We found the file, render it.
else{
res.render(pathname.substring(1), {});
}
});
}
});
app.listen(port);
注意,应该有更多的
app.use()
语句用于处理cookie、解析正文等。此外,render
的第二个参数始终为空。您可能想用{layout:xyz}
或需要进入呈现页面的通用变量来填写此内容。不确定您是否见过Express framework,但我重写了旧的MVC框架(带有路由)对于版本3:可能有一些帮助:)如果您在静态后使用
路由,这应该可以工作——如果静态找不到文件,它会将请求传递给下一个中间件。我已经按照express生成的模板应用程序使用了静态。