Ajax发布请求无法使用快速路由器

时间:2017-07-12 10:20:18

标签: ajax express post

我使用express.Router()管理我的路线。 然后使用 Ajax post 请求向其发送一些数据。但是我无法获得数据。

ajax代码:

        $.ajax({
            url: '/custom',
            type: 'POST',
            contentType: 'application/json; charset-utf-8',
            dataType: 'json',
            processData: false,
            data: JSON.stringify({ "key": "values" }),
            success: function(data) {
                console.log(data.toString());
            }
        })

快递代码:

var express = require('express');
var router = express.Router();    
router.post('/custom',  function(req, res) {
        console.log(req.body);
        console.log(req.params);
        console.log(req.query);

        res.write(JSON.stringify());
        res.end();
});

但所有日志都是空的。

1 个答案:

答案 0 :(得分:0)

问题是因为ajax中的content-type标头格式不正确。 代替 contentType: 'application/json; charset-utf-8'它应为contentType: 'application/json; charset=utf-8'

假设您正在使用bodyParser.json()中间件,这将导致无法解析正文,从而打印出一个空体。当您使用Postman发送请求时,会发送正确的标头,这就是为什么它在那里工作但不是来自ajax请求。

相关问题