在页面加载时,我在脚本标记中运行此 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"}));
那么node脚本的代码就是
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
docs告诉我们您提供的回调将由 request
事件触发。 request
event docs告诉我们 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。
关于javascript - 如何从浏览器向 Node 脚本发送数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34952004/