Bodyparser错误地解析JSON?

时间:2015-04-25 23:24:57

标签: javascript ajax node.js express

我使用带有Express的正文解析器NPM模块来解析我的服务器上的json,但由于某种原因,JSON在服务器上显示不正确。这是我的服务器代码:

...
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
...

app.route("/schedule")
    .get(function(req, res) {
        ... 
    })
    .post(function(req, res) {
        var schedule = req.body.schedule;

        console.log(req.body);

        if(schedule) {
            setSchedule(schedule);
            res.status(200).end();
        }
    });

我的客户代码:

var schedule = {
    entries: entries
};

var str = JSON.stringify(schedule);

console.log("Submitting schedule:",str);
post("/schedule", str)
    .then((res) => {
        this.completed(res.json);
    })
    .catch((res) => {
        this.failed(res.text);
    });

当我从客户端发布数据时,客户端会打印出来:

Submitting schedule: {"entries":[1430014800000,1430055600000,1430104620000,1430146380000,1430194140000,1430236920000,1430283120000,1430326860000,1430371740000,1430416380000,1430460180000,1430505480000,1430548500000,1430594460000,1430636760000,1430683260000,1430725020000,1430772060000,1430813340000,1430860920000,1430901720000,1430949900000,1430990340000,1431039060000,1431079200000,1431128520000,1431168480000,1431218220000,1431258360000,1431308160000,1431349020000,1431398040000,1431440220000,1431487800000,1431531360000,1431577260000,1431622140000,1431666540000,1431712440000,1431755640000,1431802320000,1431844680000,1431891960000,1431933660000,1431981360000,1432022580000,1432070700000,1432111560000,1432159980000,1432200540000,1432249260000,1432289580000,1432338600000,1432378860000,1432428060000,1432468500000,1432517520000,1432558560000]}

这似乎是有效的JSON,但在服务器上,req.body就是这样:

{ '{"entries":': { '1430014800000,1430055600000,1430104620000,1430146380000,1430194140000,1430236920000,1430283120000,1430326860000,1430371740000,1430416380000,1430460180000,1430505480000,1430548500000,1430594460000,1430636760000,1430683260000,1430725020000,1430772060000,1430813340000,1430860920000,1430901720000,1430949900000,1430990340000,1431039060000,1431079200000,1431128520000,1431168480000,1431218220000,1431258360000,1431308160000,1431349020000,1431398040000,1431440220000,1431487800000,1431531360000,1431577260000,1431622140000,1431666540000,1431712440000,1431755640000,1431802320000,1431844680000,1431891960000,1431933660000,1431981360000,1432022580000,1432070700000,1432111560000,1432159980000,1432200540000,1432249260000,1432289580000,1432338600000,1432378860000,1432428060000,1432468500000,1432517520000,1432558560000]': '' } }

这是唯一的密钥是{"entries":的对象,该密钥的值是一个对象,唯一的密钥是一个时间戳数组,应该作为值发送给{ {1}}。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

在我的情况下,问题是我正在使用AngularJS从前端发出请求,并且默认的POST格式设置为url编码:

$httpProvider.defaults.headers.post = {'Content-type': 'application/x-www-form-urlencoded'};

默认情况下,它设置为'application / json',因此我只是删除了这一行,然后JSON便可以正确解析。