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

我的客户正在打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"); } }); } }} 

我能够在我的app.js得到这个请求,但无法获得我传递的数据我试图search,但没有任何工作

 {{ 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); } } */ }} 

事情并不是要求和回应的事件(因为我已经看到许多人使用它来获取数据。

在这里帮助我知道最新的错误在节点上的第一次ajax

既然你发送数据为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改为application / json。

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

req.params不会做你认为的事情。

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

访问/test将用test填充req.params.route

您正在查找req.body ,它只能与身体分析器中间件一起使用。

你必须使用body-parser中间件( https://www.npmjs.org/package/body-parser ),你需要声明使用哪个badyParser

  • app.use(bodyParser.json())或者
  • app.use(bodyParser.raw())或者
  • app.use(bodyParser.text())或者
  • app.use(bodyParser.urlencoded())

    在你的主要js文件里面。 那么req.body对象将包含你的json / text / raw / urlencoded数据。