我无法读取中间件中的任何请求参数。我有一个最小的express web服务器,看起来像
'use strict';
var express = require('express');
var app = express();
//middleware
function userMiddleware(req, res, next) {
console.log('user came in. Hello ' + req.param('name'));
next();
}
//register middleware
app.use('/user', userMiddleware)
// routes
app.get('/user/:name', function(req, res) {
res.send('username : ' + req.params.name);
});
app.listen(3000);
console.log("listening on 3000...");
当我尝试访问localhost:3000/user/威廉姆斯时,我希望在日志中看到:
user came in. Hello williams
但我明白了
user came in. Hello undefined
我是否应该包含任何其他中间件,以便在中间件中填充req.params?我使用express@3.3.4
4条答案
按热度按时间np8igboo1#
我认为
app.param()
在这种情况下是非常规的,不是很直观。因为我已经有了表示中间件的函数,我可以做:mqxuamgl2#
编辑
下面的答案是不正确的。您实际上并不需要
json
或urlencoded
中间件来获取路由参数-它们只需要req.query
和req.body
工作。正如你所知道的(因为你是那里的海报之一),你在评论中提供的链接描述了这个问题:https://github.com/strongloop/express/issues/2088
问题是您试图在路由参数存在之前访问它们-中间件在路由之前运行。一个解决方案是使用该链接中建议的
app.param()
(而不是您的userMiddleware
):请注意,这将在所有路由中找到
name
参数,因此您可能希望将参数命名得更具体一些,例如username
。如果您想缩小范围,也可以检查req.url
的开头。顺便说一句,通常应该避免像在原始代码中那样使用
req.param()
;引用Express文档:Direct access to req.body, req.params, and req.query should be favoured for clarity - unless you truly accept input from each object.
老答案
把它留在这里,因为它包含的信息可能在其他情况下有用...
我相信你需要添加这个中间件,以使GET和POST变量可用:
并且:
如果您还需要在所有浏览器中使用HTTP动词,如PUT或DELETE。
您可以使用
bodyparser
而不是json
和urlencoded
,但由于文件上传,这将是一个安全漏洞。参见http://andrewkelley.me/post/do-not-use-bodyparser-with-express-js.html。此外,bodyparser
在Express 4中被弃用。注意,如果你想支持文件上传,你需要使用额外的中间件(一个好的选择是https://www.npmjs.org/package/multer)。whitzsjs3#
我遇到的最好的解决方案是使用带有
all
方法的路由器。例如:
os8fio9y4#