如何从浏览器向节点脚本发送数据?

Nic*_*ing 3 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"}));
Run Code Online (Sandbox Code Playgroud)

然后是节点脚本的代码

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);
Run Code Online (Sandbox Code Playgroud)

但是在console.log中,我在任何地方都看不到我的{"hello":"goodbye"}对象.如何访问此对象?

Exp*_*lls 5

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)));
Run Code Online (Sandbox Code Playgroud)

要么

// ES5
var body = '';
request.on('data', function (chunk) {
   body += chunk;
});
request.on('end', function(){
  console.log(JSON.parse(body));
});
Run Code Online (Sandbox Code Playgroud)

有很多http服务器实现,将为您抽象这个过程并让您request.body使用.body-parser是一个很好的例子,甚至会为你解析JSON.

  • 很好的答案. (2认同)