在页面加载时,我正在脚本标记中运行此javascript:
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "http://lvh.me:1337", true);
xhttp.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
xhttp.send(JSON.stringify({hello:"goodbye"}));
然后,节点脚本的代码是
var http = require('http');
http.createServer(function (request, response) {
response.writeHead(200, {
'Content-Type': 'text/plain',
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept"
});
console.log(request);
response.end("");
}).listen(1337);
但是在console.log中,我什么都看不到我的{“ hello”:“ goodbye”}对象。我如何访问该对象?
该createServer
文件告诉我们,您提供的回调将被触发request
事件。该request
事件的文档告诉我们,request
(第一个参数)是一个http.IncomingMessage
。它没有body
属性,但是实现了ReadableStream,您可以侦听'data'
事件以收集数据:
// ES2015 (all of the below is supported in current NodeJS)
let body = '';
request.on('data', chunk => body += chunk);
request.on('end', () => console.log(JSON.parse(body)));
或者
// ES5
var body = '';
request.on('data', function (chunk) {
body += chunk;
});
request.on('end', function(){
console.log(JSON.parse(body));
});
有很多http服务器实现,可以为您抽象该过程并为您request.body
提供帮助。body-parser
是一个很好的例子,甚至可以为您解析JSON。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句