gpt4 book ai didi

node.js - xxx-form-encoded 到 application/json

转载 作者:太空宇宙 更新时间:2023-11-04 00:00:09 25 4
gpt4 key购买 nike

我在后端的登录功能接受来自 POSTMAN 的 xxx-form-encoded 格式的参数。当我将格式更改为 application/json 时,出现错误。关于如何接收 request.body 有什么想法吗?

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。

您可以使用body-parser来实现它。

如果您使用的是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 }));

来自 body-parser 文档:

bodyParser.urlencoded([options])

Returns middleware that only parses urlencoded bodies and only looksat requests where the Content-Type header matches the type option.This parser accepts only UTF-8 encoding of the body and supportsautomatic inflation of gzip and deflate encodings.

A new body object containing the parsed data is populated on therequest object after the middleware (i.e. req.body). This object willcontain key-value pairs, where the value can be a string or array(when extended is false), or any type (when extended is true).

阅读body-parser documentation了解详情。

关于node.js - xxx-form-encoded 到 application/json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55158584/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com