【问题标题】:Unable to post using Jquery for nodeJS application无法使用 Jquery 发布 nodeJS 应用程序
【发布时间】:2019-01-20 23:07:42
【问题描述】:

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

客户端脚本:

    $(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

能否请您指导我为什么无法接收数据?提前谢谢你。

【问题讨论】:

标签: jquery node.js ajax


【解决方案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',
    ...
});

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 如果我不对对象进行字符串化,我不应该在服务器端使用bodyParser吗..?
    猜你喜欢
    • 2020-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-15
    • 2018-05-27
    • 1970-01-01
    • 1970-01-01
    • 2017-09-17
    相关资源
    最近更新 更多