gpt4 book ai didi

node.js - Express.js/Node.js : Order of Routes important and where to put next()?

转载 作者:太空宇宙 更新时间:2023-11-03 23:39:40 24 4
gpt4 key购买 nike

我的路线和路径设置如下:

var path1        = express.Router()
, path2 = express.Router()
// .. more modules, e.g. express-jwt ..

module.exports = function(app, passport) {

var path1Func = function(req, res) {

return MODEL.findById(req.params.id, function(err, model) {

if(!model) {
res.statusCode = 404;
return res.send({ status: '404 Not found' });
}

if(!err) {
return res.send({ status: 'OK', model:model });
} else {
res.statusCode = 500;
return res.send({ status: '500 Server error' });
}
});
};

// .. other functions which essentially look like above path1Func ..

path1.get('/subPath', path1Func );
path2.get('/otherSubPath', path2Func );
path2.post('/entirelyOtherSubPath', otherPath2Func );

app.use('/path1', path1);
app.use('/path2', path2);

app.use('/grid', expressJwt({secret: secret})); // Protect Paths
}

现在,根据我的 HTTP 请求、POST、GET 等的顺序,它们会被执行或返回 404 not find,这意味着 Express 不会解析某些请求,具体取决于 path1.getpath2.getpath2.post 的顺序。

express1Order

express2Order

上面的图片描绘了我看到的 404,具体取决于我的 paths.js 文件中路由声明的顺序。当我重新调整订单时,404 消失了,我得到了我想要的输出

这就是为什么我想使用 next() 来帮助我解决这个问题 - 请记住,我使用大量 app.use 使事情变得复杂。到目前为止,我自己还没能做到这一点。我仍然不清楚 next() 到底是什么以及如何在上面的示例中使用它来使我的路由器在每个路由中工作。为了节省空间,我没有把其他路由放在这里,但我的 API 已经相当大了,而且还会变得更大。

无论我的 POSTGET 请求的顺序如何,这里有什么方法可以让我的应用提供内容?

最佳答案

您所显示的特定请求收到 404 的原因是因为您没有匹配的路由模式。

您正在请求 /grid/dates/:val 但您只有 /grid 路线。即使您将 /grid 更改为 /grid/dates/:val,您仍然不会响应请求,因为所有 expressJwt()所做的是验证请求,然后将执行传递给下一个处理程序。因此,考虑到这一点,您可以尝试以下操作:

app.use('/grid/dates/:val',
expressJwt({secret: secret}),
function(req, res) {
res.send(200, 'hello world!');
});

关于node.js - Express.js/Node.js : Order of Routes important and where to put next()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26219291/

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