Node.js xxx表单编码为application/json
后端的“我的登录”功能接受来自POSTMAN的xxx格式编码的参数。。将格式更改为application/json时出错。关于如何接收请求,你有什么想法吗Node.js xxx表单编码为application/json,node.js,json,postman,Node.js,Json,Postman,后端的“我的登录”功能接受来自POSTMAN的xxx格式编码的参数。。将格式更改为application/json时出错。关于如何接收请求,你有什么想法吗 authenticate: function(req, res, next) { userModel.findOne({email:req.body.email}, function(err, userInfo){ if (err) { n
authenticate: function(req, res, next) {
userModel.findOne({email:req.body.email}, function(err, userInfo){
if (err) {
next(err);
} else {
console.log(`The bcrypt value: ${bcrypt.compareSync(req.body.password, userInfo.password)}`)
if(userInfo != null && bcrypt.compareSync(req.body.password, userInfo.password)) {
const token = jwt.sign({id: userInfo._id}, req.app.get('secret'), { expiresIn: '1h' });
res.json({status:"success", message: "user found!!!", data:{user: userInfo, token:token}});
}else{
res.json({status:"error", message: "Invalid email/password!!!", data:null});
}
}
});
}
我认为您需要添加一个中间件,将您的请求体解析为json 您可以使用
主体解析器来实现它
如果您使用的是express,您可以执行以下操作:
var express = require("express");
var bodyParser = require("body-parser");
var app = express();
app.use(bodyParser.json({}));//this line is required to tell your app to parse the body as json
app.use(bodyParser.urlencoded({ extended: false }));
从正文解析器文档:
bodyParser.urlencoded([options])
返回仅解析URL编码的实体且仅查找的中间件
在内容类型标头与类型选项匹配的请求中。
此解析器只接受主体的UTF-8编码,并支持
gzip的自动充气和放气编码
包含已解析数据的新body对象将填充到
中间件之后的请求对象(即请求主体)。这个物体会
包含键值对,其中值可以是字符串或数组
(扩展为false时)或任何类型(扩展为true时)
有关详细信息,请阅读。bodyParser
也可以作为express
变量的属性提供,无需另一个依赖项。