简体   繁体   English

jQuery .ajax POST 请求在 Node 接收时有一个空的主体

[英]jQuery .ajax POST request has an empty body when received by Node

For some reason when I make an ajax post using jQuery, the body, as received by node is empty.出于某种原因,当我使用 jQuery 制作 ajax 帖子时,节点收到的正文是空的。 Here is my ajax post:这是我的ajax帖子:

jQuery jQuery

var formData = {
    'order': order,
    'words': 'words'
};

$.ajax({

    type: 'post',

    url: 'https://example.com/charge',    
    processData: false,
    data: JSON.stringify(formData),

    contentType: 'json', 

    xhrFields: {
        withCredentials: false
    },  

    headers: {

    }, 

    success: function (data) {
        console.log('Success');
        console.log(data);

    },  

    error: function () {
        console.log('We are sorry but our servers are having an issue right now');
    }
})

And here is my node code:这是我的节点代码:

Node节点

app.js

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use('/', routes);

routes/index.js

router.post('/charge', function(req, res) {
    console.log(req.body);
} //This always logs {}

I have no idea what I could be doing wrong here.我不知道我在这里做错了什么。 My browser even shows a payload and the post request (the formData object) but node logs nothing.我的浏览器甚至显示了有效负载和发布请求( formData对象),但节点没有记录任何内容。 Any ideas?有任何想法吗?

Use ajax request like this:像这样使用ajax请求:

$.ajax({
    type: 'post',
    url: 'https://example.com/charge',   
    data: formData,
    xhrFields: {
        withCredentials: false
    },  
    headers: {

    }, 
    success: function (data) {
        console.log('Success');
        console.log(data);
    },  
    error: function () {
        console.log('We are sorry but our servers are having an issue right now');
    }
})

Mine was not working too, but solved by using,我的也没有工作,但通过使用解决了,

contentType: 'application/json',
data: JSON.stringify(formdata),

Check following api检查以下api

By setting the processData option to false, the automatic conversion of data to strings is prevented.通过将 processData 选项设置为 false,可以防止数据自动转换为字符串。

If you want to use json type, processData must be setted true如果要使用json类型,processData必须设置为true

Jquery processData Jquery 进程数据

This may be a late reply, but please also note the JQuery ajax documentation:这可能是一个迟到的回复,但也请注意 JQuery ajax 文档:

Object must be Key/Value pairs.对象必须是键/值对。

This took me 2 hours (server received empty body) because I was trying to post a more 'complicated' object.这花了我 2 个小时(服务器收到空的正文),因为我试图发布一个更“复杂”的对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM