Javascript 如何从浏览器向节点脚本发送数据?
在页面加载时,我在脚本标记中运行此javascript:Javascript 如何从浏览器向节点脚本发送数据?,javascript,json,node.js,Javascript,Json,Node.js,在页面加载时,我在脚本标记中运行此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
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”:“再见”}对象。如何访问此对象?通知我们您提供的回调将由请求
事件触发。告诉我们请求
(第一个参数)是一个。这没有正文
属性,但它实现了,并且您可以侦听'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)));
或
有很多http服务器实现将为您抽象这个过程,并提供一个
request.body
。这是一个很好的例子,甚至可以为您解析JSON。它说它是未定义的。请求
对象是一个流,所以我认为您需要处理数据
事件。我如何在@MinusFour中做到这一点?您完全正确。。。典型的express主体解析器
。。。!非常感谢,你肯定知道一些事情。我还是有麻烦。现在我得到了语法错误:输入意外结束
。当我注释掉console.log(JSON.parse(body)),它就消失了
@NickManning将显示body
没有有效的JSON。尝试一下控制台.log(body)@ExplosionPills---这样做会输出[object object]
。没关系,对不起。我忘了在我试图弄清楚的时候,我在html文件中取出了JSON.stringify
。谢谢@ExplosionPills和TJ Crowder。
// ES5
var body = '';
request.on('data', function (chunk) {
body += chunk;
});
request.on('end', function(){
console.log(JSON.parse(body));
});