我有这个作为我的快速服务器的配置
app.use(app.router);
app.use(express.cookieParser());
app.use(express.session({ secret: "keyboard cat" }));
app.set('view engine', 'ejs');
app.set("view options", { layout: true });
//Handles post requests
app.use(express.bodyParser());
//Handles put requests
app.use(express.methodOverride());
但是当我在我的路由中请求req.body.something时,我得到了一些错误,指出body是未定义的。下面是一个使用req的路由示例。身体:
app.post('/admin', function(req, res){
console.log(req.body.name);
});
我读到这个问题是由缺乏app.use(express.bodyParser())引起的;但你可以看到,我把它叫做路线之前。
有线索吗?
浪费了很多时间:
这取决于客户端请求中的Content-Type
服务器应该有不同的,以下app.use()之一:
app.use(bodyParser.text({ type: 'text/html' }))
app.use(bodyParser.text({ type: 'text/xml' }))
app.use(bodyParser.raw({ type: 'application/vnd.custom-type' }))
app.use(bodyParser.json({ type: 'application/*+json' }))
来源:https://www.npmjs.com/package/body-parser bodyparsertextoptions
例子:
对我来说,
在客户端,我有以下标题:
Content-Type: "text/xml"
因此,在服务器端,我使用:
app.use(bodyParser.text({type: 'text/xml'}));
然后,要求。身体工作正常。
好吧,这可能听起来很蠢,但对我来说很管用。
作为一个完全的初学者,我没有意识到写作:
router.post("/", (res, req) => {
console.log(req.body);
req.send("User Route");
});
是错的!
你必须确保你以正确的顺序传递post/get的参数(req,res):并相应地调用它们:
router.post("/", (req, res) => {
console.log(req.body);
res.send("User Route");
});