[英]Escaping /: routes in Express in order to load js and css
How can I escape routes in Express and Node.js when using the /: notation? 使用/:表示法时,如何在Express和Node.js中转义路由? Here's what I'm doing:
这是我在做什么:
app.get('/:route1/:route2', function(req, res){
var route1 = req.params.route1;
var route2 = req.params.route2;
MongoClient.connect(MongoUrl, function(err, db) {
if(err) throw err;
db.collection(route1)
.findOne({'_id' : new ObjectID(route2)},
function(err, doc){
res.send(doc);
});
});;
But by doing that, it won't load the js or css. 但是这样做,将不会加载js或CSS。 I've tried if statements to no avail:
我试过if语句无济于事:
if(req.params.route1 !== 'javascripts'){//then do something}
Are you using the connect static middleware ? 您是否在使用connect静态中间件 ?
app.use(express.static(__dirname + 'public'))
This says "any request to a file in the /public
folder, serve it as a static file". 这表示“对
/public
文件夹中的文件的任何请求,都将其作为静态文件使用”。
Make sure this appears above any app.get
routes, so it will be used first. 确保此名称显示在所有
app.get
路线上方,因此将首先使用它。
you should move your static middleware above your route 您应该将静态中间件移到路线上方
app.use(express.static(path.join(__dirname, 'public')));
app.use(app.router);
app.get('/:route1/:route2', api.function);
First, without any knowledge of what you're doing or how your app is structured, I can't say for sure, but: 首先,在不知道自己在做什么或应用程序如何结构的情况下,我不能肯定地说,但是:
What you're doing (routes like /:var1/:var2
) is a code smell to me. 你在做什么(像
/:var1/:var2
这样的路由)对我来说是代码的味道。 If api.function
looks something like 如果
api.function
看起来像
if (req.params.var1 == 'foo') {
// do stuff
} else if (req.params.var1 == 'bar') {
// do other stuff
}
...that's not really the correct way to structure an Express application. ...这并不是构造Express应用程序的正确方法。 In general, it should look more like
一般来说,它看起来应该更像
app.get('/foo/:var2', function(req, res) {
// do stuff
});
app.get('/bar/:var2', function(req, res) {
// do other stuff
});
That being said, if you really need to have your route handler ignore a certain value, you could just call next
: 话虽如此,如果您确实需要让路由处理程序忽略某个值,则可以调用
next
:
app.get('/:route1/:route2', function(req, res, next) {
if (req.params.route1 == 'javascripts') next();
else {
// do something
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.