无法在快速中间件中获取请求参数 [英] Cannot get request params in express middleware
本文介绍了无法在快速中间件中获取请求参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我无法读取我的中间件中的任何req.params。我有一个最小的快速网络服务器,看起来像
I am not able to read any req.params in my middleware. I have a minimal express web server that looks like
'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 / williams时,我希望在日志中看到:
When I try to hit localhost:3000/user/williams , I expect to see in the log :
user came in. Hello williams
但我看到
user came in. Hello undefined
我应该包括任何其他中间件,以便req.params填充在中间件中?
我使用 express@3.3.4
Should I include any other middleware so that the req.params is populated in the middleware ?
I'm using express@3.3.4
推荐答案
我认为 app.param()
在这种情况下是非常规的,并不真正直观。因为我已经有代表中间件的功能,我可以这样做:
I think app.param()
is unconventional in this case and not really intuitive. Since I already had the function representing the middleware, I could do :
//middleware
function userMiddleware(req, res, next) {
console.log('user came in. Hello ' + req.params.name);
next();
}
// routes
app.get('/user/:name', userMiddleware, function(req, res) {
res.send('username : ' + req.params.name);
});
这篇关于无法在快速中间件中获取请求参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文