【问题标题】:xxx-form-encoded to application/jsonxxx-form-encoded 到 application/json
【发布时间】:2019-03-14 18:05:57
【问题描述】:

我在后端的登录功能接受来自 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});

                        }
                    }
                });
    }

【问题讨论】:

    标签: node.js json postman


    【解决方案1】:

    我认为您需要添加一个将您的请求正文解析为 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 }));
    

    来自正文解析器文档:

    bodyParser.urlencoded([options])

    返回仅解析 urlencoded 正文且仅查找的中间件 在 Content-Type 标头与 type 选项匹配的请求中。 此解析器仅接受正文的 UTF-8 编码并支持 gzip 和 deflate 编码的自动膨胀。

    一个包含解析数据的新主体对象被填充到 中间件之后的请求对象(即req.body)。该对象将 包含键值对,其中值可以是字符串或数组 (当扩展为假时),或任何类型(当扩展为真时)。

    阅读body-parser documentation了解详情。

    【讨论】:

    • bodyParser 也可作为express 变量的属性使用,无需其他依赖项。
    猜你喜欢
    • 2017-09-11
    • 1970-01-01
    • 2016-04-13
    • 2012-04-09
    • 1970-01-01
    • 2015-12-20
    • 1970-01-01
    • 2019-10-26
    • 2016-07-17
    相关资源
    最近更新 更多