繁体   English   中英

使用 http node.js 在另一台服务器上处理来自服务器的发布数据

[英]handling posted data from a server on another server with http node.js

我有两台服务器(A 和 B),我想从服务器 A 发布数据并在服务器 B 上处理它,但是从服务器 A 发送的请求中没有数据属性。注意:我希望所有这些工作都由 pure 完成node.js和http模块服务器A:

var http = require('http')

const data = {name: 'karo', age: 18, email: 'helloworld@gmail.com'}
http.createServer(function(req, res){
        res.writeHead(200, {'Content-Type' : 'application\json'})
        res.end(JSON.stringify(data))
        

}).listen(1337,'127.0.0.1')

const options = {
    protocol: "http:",
    hostname: "127.0.0.1", 
    port: "1338" ,
    path: "/", 
    method: "GET", 
  };
     
 // Sending the request
 var post_req = http.request(options, function(res) {
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
        console.log('Response: ' + chunk);
    });
})
post_req.write(JSON.stringify(data)) 
post_req.end()

服务器乙:

http.createServer((req, res) => {
  console.log(req)
}).listen(1338,'127.0.0.1')

我可以通过 axios 模块做到这一点,但不能通过 http

你的方法有很多问题,首先,你说你想将数据发布到服务器 B,但是在服务器上的请求中,你使用method: "GET" ,将数据写入 get 请求不起作用,它没有要写入的请求主体。

除此之外,您的服务器 A 看起来还不错。

在服务器 B 上, req只是引用传入的 stream 请求到您的服务器。 为了与发送给它的数据进行交互,您必须使用req.on('data' () => {})方法从 stream 获取传入数据。 最后,您想要从传入请求中收集数据,将其加起来并将创建的缓冲区中的数据解析回 object。

所以你的服务器 B 实现应该看起来更像这样:

var http = require('http')

http.createServer((req, res) => {
  const chunks = [];
  // whenever new data comes in through the stream, add it to the chunks array
  req.on('data', chunk => chunks.push(chunk));
  req.on('end', () => {
    // once the request is done, gather the data and parse it back to an object
    const data = Buffer.concat(chunks);
    console.log('Data: ', data);
    console.log('JSON:', JSON.parse(data.toString()));
  })
}).listen(1338, '127.0.0.1')

和服务器 A 是这样的:

var http = require('http')

const data = {
  name: 'karo',
  age: 18,
  email: 'helloworld@gmail.com'
}
http.createServer(function(req, res) {
  res.writeHead(200, {
    'Content-Type': 'application\json'
  })
  res.end(JSON.stringify(data))


}).listen(1337, '127.0.0.1')

const options = {
  protocol: "http:",
  hostname: "127.0.0.1",
  port: "1338",
  path: "/",
  method: "POST", // <-- POST the data
};

// Sending the request
var post_req = http.request(options, function(res) {
  res.setEncoding('utf8');
  res.on('data', function(chunk) {
    console.log('Response: ' + chunk);
  });
})
post_req.write(JSON.stringify(data))
post_req.end()

服务器 B 端的 output 将如下所示:

❯ node b.js
Data:  <Buffer 7b 22 6e 61 6d 65 22 3a 22 6b 61 72 6f 22 2c 22 61 67 65 22 3a 31 38 2c 22 65 6d 61 69 6c 22 3a 22 68 65 6c 6c 6f 77 6f 72 6c 64 40 67 6d 61 69 6c 2e ... 5 more bytes>
JSON: { name: 'karo', age: 18, email: 'helloworld@gmail.com' }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM