NodeJS如何获取服务器中的数据,通过POST从jquery ajax调用发送

Gop*_*kla 5 ajax jquery post node.js

我的客户正在进行ajax调用

{{


        function callNode(){

        console.log("I am called");
        var data = {"emailId":"gopal@gmail.com"};



        $.ajax({
            type: 'POST',
            data: JSON.stringify(data),
           /* data: {
                blob: {wob:"1",job:"2", ar:[1,2,{a:'b'}]}
            },*/
            contentType: "application/javascript",
            //contentType: "application/x-www-form-urlencoded",
            dataType:'json',
            url: 'http://localhost:3000/notification',                      
            success: function(data) {
                console.log('success');
                console.log(JSON.stringify(data));                               
            },
            error: function(error) {
                console.log("some error in fetching the notifications");
             }

        });
    }
}}
Run Code Online (Sandbox Code Playgroud)

我可以在我的app.js中获取此请求,但无法获取我传递的数据,我试图搜索但没有任何工作

{{

      app.post('/notification', function(req, res) {
      JSON.stringify(req.params);


      /*
       var body;
       req.on('data', function(chunk) {
        console.log("Received body data:");       
         body += chunk;
      });

       // the end event tells you that you have entire body
      /*req.on('end', function () {
       try {
      var data = JSON.parse(body);
       colnosole.log(data);

    } catch (er) {
      // uh oh!  bad json!
      res.statusCode = 400;
      return res.end('error: ' + er.message);
    }

  }
   */


}}
Run Code Online (Sandbox Code Playgroud)

事情是它没有进入任何请求和响应事件(因为我看到很多人使用它来获取数据.

在节点上第一次使用ajax时,请帮助我知道这里有什么问题

V31*_*V31 3

由于您以 json 形式发送数据,因此需要更改 contentType,因此 ajax 调用应该是:

$.ajax({
        type: 'POST',
        data: JSON.stringify(data),
       /* data: {
            blob: {wob:"1",job:"2", ar:[1,2,{a:'b'}]}
        },*/
        contentType: "application/json",
        //contentType: "application/x-www-form-urlencoded",
        dataType:'json',
        url: 'http://localhost:3000/notification',                      
        success: function(data) {
            console.log('success');
            console.log(JSON.stringify(data));                               
        },
        error: function(error) {
            console.log("some error in fetching the notifications");
         }

    });
Run Code Online (Sandbox Code Playgroud)

在这里您可以看到 contentType 更改为 application/json。

在服务器端,您需要检查 request.body 才能获取数据,而不是 request.params。