这是我的代码:
var express = require("express");
var bodyParser = require("body-parser");
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.get('/',function(req,res){
res.sendfile("index.html");
});
app.post('/login',function(req,res){
console.log(req.body)
var user_name=req.body.user;
var password=req.body.password;
console.log("User name = "+user_name+", password is "+password);
res.end("yes");
});
app.listen(3000,function(){
console.log("Started on PORT 3000");
})
我在 post 方法函数中设置了一个控制台,但它显示:
{}
User name = undefined, password is undefined
我无法从响应中获取任何数据。我有查找文档,但找不到任何错误。我还是不明白。我犯了什么错误?
最佳答案
您应该使用 Postman 发送数据,并在 header 中添加 content-type:application/json
。这将确保服务器接收到 JSON 格式的数据。
关于javascript - 我无法从 Node js + Express JS 中的 req.body 获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35346471/