Home > front end >  handling posted data from a server on another server with http node.js
handling posted data from a server on another server with http node.js

Time:01-28

I have Two servers(A and B) and I want to post data from server A and handle it on the server B but the is no data attribute in the request sent from server A. note: I want all these work be done by pure node.js and http module Server A:

var http = require('http')

const data = {name: 'karo', age: 18, email: '[email protected]'}
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()

Server B:

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

I can do this by axios module but not by http

CodePudding user response:

There are multiple problems with your approach here, first off all, you say you want to post data to server B, yet in the request on server a you use method: "GET", writing data to a get request doesn't work, it doesn't have a request body to write to.

Other than that your sever A looks fine.

On server B, req is just referencing the incoming stream of requests to your server. In order to interact with data sent to it, you have to get the incoming data from the stream, by using the req.on('data' () => {}) method. In the end you want to gather the data from incoming requests add it up and parse the data from the created buffer back to an object.

So your server B implementation should look more like this:

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')

and server A like this:

var http = require('http')

const data = {
  name: 'karo',
  age: 18,
  email: '[email protected]'
}
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()

The output on server B's side will look like this:

❯ 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: '[email protected]' }
  • Related