无法使用Jquery发布NodeJS应用程序

时间:2018-08-14 07:03:51

标签: jquery node.js ajax

我无法将数据发布到服务器并收到超时错误。请参见下面的代码:

客户端脚本:

    $(document).ready(function(){
            $('#form1').on('submit',function(e) {
                e.preventDefault();
                    $.ajax({
                    type: "POST",
                    url: "/",
                    timeout: 2000,
                    data : JSON.stringify({ image: "yo", text: "apples" }),
                    dataType : 'json',
                    success: function(data) {
                        alert('Success!')
                    },
                    error: function(jqXHR, textStatus, err) {
                        alert('text status '+textStatus+', err '+err)
                    }
            });
            })
    })

服务器端脚本:

    app.use(bodyParser.json());
    app.post('/', function (req, res){

        console.log(req.body);
        console.log('req received');

    });

在服务器上,我看到的输出为

    APP STARTED ON PORT - 3000
    {}
    req received

您能为我为什么无法接收数据提供指导吗?预先谢谢你。

2 个答案:

答案 0 :(得分:1)

超时的原因是您没有响应请求。即使您的api没有任何结果,您也应该至少使用状态码来响应请求。

res.sendStatus(200);

body-parser默认仅解析content-typeapplication/json的请求。尝试将contentType: 'application/json; charset=UTF-8'添加到jQuery ajax选项。

$.ajax({
    ...
    contentType: 'application/json; charset=UTF-8',
    ...
});

答案 1 :(得分:0)

正文始终作为对象发送。...不要对其进行字符串化!