gpt4 book ai didi

javascript - 在 Node 中设置基于文件系统的路由

转载 作者:行者123 更新时间:2023-11-30 18:27:52 24 4
gpt4 key购买 nike

我真的很喜欢 PHP 在服务页面方面提供的简单性,一切都基于文件系统。我想用 Node 做同样的事情。我尝试了一种像这样用于 View 的路由设置,但破坏了我的公共(public)文件夹:

//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
}});
});

那么...

在 Node 中设置基于文件系统/php 样式的路由的最佳方法是什么?

最佳答案

我认为我构建的正是您正在寻找的东西。我用它来提供 .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} 或需要进入呈现页面的通用变量来填充它。

关于javascript - 在 Node 中设置基于文件系统的路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10377799/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com