使用jquery ajax调用节点js服务器

时间:2018-03-12 20:27:08

标签: jquery node.js ajax

这个问题可能很简单。但我无法在我的代码中找出问题。

我想使用jquery ajax调用将数据发送到节点js api。

这是我的节点js API

.post('/createPerson', global.bodyParserJson, function (req, res, next) {           
        console.log(req.body);

      // My code going here
    })

来自客户端的 ajax 电话。

    $.ajax({
        type: 'post',
        url: serverLocation + "/api/dashboard/createPerson",
        dataType: 'json',
        data:  { Name: "John", Age: 20 },
        contentType: "application/json; charset=UTF-8",
        success: function (data) {
            console.log('Sucss');            
        },
        error: function (textStatus, errorThrown) {
           console.log('Err');

        }
    });

API被ajax调用命中,但数据未通过。它是空的。我尝试使用postman调用api,它运行良好,这意味着json数据到达服务器端。

你能告诉我在我的代码中找到问题的线索吗?

1 个答案:

答案 0 :(得分:1)

你必须使用JSON.stringify首先将你的对象序列化为JSON字符串,这样你的服务器才能理解它是一个JSON:

$.ajax({
        type: 'post',
        url: serverLocation + "/api/dashboard/createPerson",
        dataType: 'json',
        data:  JSON.stringify({ Name: "John", Age: 20 }),
        contentType: "application/json; charset=UTF-8",
        success: function (data) {
            console.log('Sucss');            
        },
        error: function (textStatus, errorThrown) {
           console.log('Err');

        }
    });

这应该有效