如何从浏览器将数据发送到节点脚本

How do I send data to a node script from a browser?

本文关键字:节点 脚本 数据 浏览器      更新时间:2023-09-26

在页面加载时,我在脚本标签中运行此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);

但是在控制台.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.bodybody-parser 就是一个很好的例子,甚至可以为您解析 JSON。