[英]Sending data to server in node
I am sending data to to server with AJAX using我正在使用 AJAX 将数据发送到服务器
function post(url) {
return new Promise(function(resolve, reject) {
var req = new XMLHttpRequest();
req.open('POST', url);
req.onload = function() {
if (req.status == 200) {
resolve(req.response);
}
else {
reject(Error(req.statusText));
}
};
req.onerror = function() {
reject(Error("Network Error"));
};
var data = moldData();
alert(JSON.stringify(data , null , 2 ))
req.send( data );
});
}
send.addEventListener('click', function(){
post('http://localhost:8080/order').then(function(){
alert('send')
}).catch(function(e){
alert(e)
})
}
on server side i am using在服务器端我正在使用
app.post('/order', function( req , res ){
console.log('sup')
console.log("=================\n" , req.body)
})
But whenever i post it , the promise does not get resolved nor rejected eg then nor catch gets executed.但是每当我发布它时,承诺不会得到解决或拒绝,例如 then 或 catch 被执行。 And on server side it just prints
在服务器端它只是打印
"===============" "[Object object]" "===============""[对象对象]"
I am using body parser eg我正在使用身体解析器,例如
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.raw())
app.use(bodyParser.text())
I am fairly new to the backend development, why is this happening?我对后端开发还很陌生,为什么会这样? What causes this?
这是什么原因造成的? using
使用
console.log(JSON.stingify(req.body,null,2))
results in the same output.结果相同的输出。
Thanks for help!感谢帮助!
// Although the one part of question got answered. // 虽然问题的一部分得到了回答。 The main question was why req.body isnt printed , but instead , [Object object] is printed.
主要问题是为什么不打印 req.body ,而是打印 [Object object]。
Your server side code logs two things and then stops.您的服务器端代码记录两件事然后停止。
The browser waits for a while and should eventually time out and reject the promise.浏览器等待一段时间,最终应该超时并拒绝承诺。
You have to send a response!您必须发送回复!
Look at the hello world example :看看你好世界的例子:
res.send('Hello World!');
You need to stringify the server response when logging it.您需要在记录服务器响应时对其进行字符串化。
console.log("=================\n" , JSON.stringify(req.body))
If you want to "pretty-print" the output, you can do this:如果你想“漂亮地打印”输出,你可以这样做:
console.log("=================\n" , JSON.stringify(req.body, null, 4))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.