2014-09-11 42 views
5

从jQuery的AJAX调用发送获取数据我的客户端调用Ajax怎样的NodeJS在服务器上,通过POST

{{ 


     function callNode(){ 

     console.log("I am called"); 
     var data = {"emailId":"[email protected]"}; 



     $.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"); 
      } 

     }); 
    } 
}} 

我能在我的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); 
    } 

    } 
    */ 


}} 

事情数据它不是的请求和响应(任何事件里面来了,因为我已经看到以此来获取数据了不少人。

帮助我知道什么是错在这里的第一次阿贾克斯节点

回答

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"); 
     } 

    }); 

在这里你可以看到的contentType改为应用/ JSON。

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

+1

It Worked Thanks V31。只有你提到的变化才能让它运行:) – 2014-09-11 15:50:30

1

req.params没有做什么,你认为它。

app.get('/:route', function(req, res) { 
    console.log(req.params.route); 
}); 

参观/test将填充req.params.routetest

您正在寻找req.body,它只能与body-parser中间件一起使用。

1

你必须用身体解析器的中间件(https://www.npmjs.org/package/body-parser),你需要声明一个badyParser使用

  • app.use(bodyParser.json())或
  • app.use(bodyParser。生())或
  • app.use(bodyParser.text())或
  • app.use(bodyParser.urlencoded())

    你的主JS文件中。然后req.body对象将包含您的JSON /文本/生/ url编码数据。

相关问题