我的客户正在拨打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中获得此请求,但无法获得我正在传递的数据
我试图搜索,但没有任何 react
{{
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);
}
}
*/
}}
事情是它不会出现在任何请求和响应事件中(因为我已经看到很多人使用它来获取数据。
帮助我知道这是什么问题,这是 Node 上的首次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。
关于jquery - NodeJS如何通过POST从jquery ajax调用发送的服务器中获取数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25782375/