【问题标题】:two different project request json parse error两个不同的项目请求json解析错误
【发布时间】:2016-12-24 16:41:44
【问题描述】:

我正在尝试做两个不同的项目请求。我请求一个使用请求模块的其他项目使用 express 但在 express 项目中出现 json 解析错误

示例对象

var data= {
    User: {
        ID: 123
    },
    Text: 'hello world'
};

 request.post({
            headers: { 'content-type': 'application/x-www-form-urlencoded' },
            url: "url/test",
            body: JSON.stringify(data)
        }, function (error, response, body) {

            logger.debug("error : ", error);
            logger.debug("body : ", body);

        });

听一个快递项目

app.post('/test', function(req, res) {

    try {
        res.header('Access-Control-Allow-Origin', req.headers.origin || "*");
        res.header('Access-Control-Allow-Methods', 'POST');
        res.header('Access-Control-Allow-Headers', 'Content-Type');

        console.log(req.body);
        var x = JSON.parse(req.body);

        res.send(200);

    } catch (error) {

        res.send(200);
    }
});

req.body 是

{ '{"User":{"ID":123},"Text":"hello world"}': '' }

错误是

SyntaxError: 位置 1 处 JSON 中的意外标记 o

击败额外的单引号 { '{"User":{"ID":123},"Text":"hello world"}': '' }

【问题讨论】:

标签: node.js express request


【解决方案1】:

req.body 是一个对象,而不是一个简单的字符串。 Javascript 解释器已经解析了它。这就是为什么您会看到神秘的 Unexpected token o in JSON at position 1 消息,尽管 JSON 中没有“o”; JSON.parse 正在尝试对非字符串进行字符串操作。

【讨论】:

    【解决方案2】:

    您应该在您的 express 应用配置中添加一些选项,并使用 npm install body-parser 安装 body-parser 包,如下所示:

    var bodyParser = require('body-parser');
    app.use(bodyParser.json({
    keepExtensions: true
    }));
    app.use(bodyParser.urlencoded());
    

    【讨论】:

    • 我一直在尝试这样 // Body Parser app.use(bodyParser.json()); // 支持 JSON 编码的主体 app.use(bodyParser.urlencoded({ // 支持 URL 编码的主体扩展: true })); // Body Parser end 我会试试你的方法。我写结果
    • 抱歉没有变化 :(
    • 使用JSON.parse(JSON.stringify((req.body))解析json值
    猜你喜欢
    • 2011-10-05
    • 1970-01-01
    • 2018-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多