Home > database >  Handling posted data
Handling posted data

Time:12-27

I have two Servers(A and B).I post a data with axios from the server A to B and console.log it in the other server, but the data is not in the posted message from server A.

Server A:

var http = require('http')
var axios = require('axios')

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 api = axios.create({baseURL: 'http://127.0.0.1:1338'})
api.post('/', {
    data: JSON.stringify(data)
})
.then(res => {
     console.log(res)
})
.catch(error => {
     console.log(error)
})

Server B :

var http = require('http')

http.createServer(function(req, res){
        console.log(req);
        res.writeHead(200, {'Content-Type' : 'text/plain'})
        res.end('hello world')

}).listen(1338,'127.0.0.1')

I also tried http request and its the same

CodePudding user response:

log res.data instead of res

api.post('/', {
    data: JSON.stringify(data)
})
.then(res => {
     //log res.data instead of res
     console.log(res.data)
})
.catch(error => {
     console.log(error)
})

If you want to log th data received from server A in server B:

npm i body in server B dir. server B:

var http = require('http');

var anyBody = require("body/any")

http.createServer(function(req, res){
    console.log(req);
    anyBody(req, res, {}, (err,data)=>{console.log(data)});
    res.writeHead(200, {'Content-Type' : 'text/plain'});
    res.end('hello world')

}).listen(1338,'127.0.0.1');

CodePudding user response:

The request object req does not contain the request body as a string, because the body is streamed by the client. Writing it into a string would mean waiting for the stream to finish, before the request handler can start building the response object res. But that would be very inflexible.

The following code instructs the request handler to wait for the body and then log it:

http.createServer(async function(req, res) {
  var body = "";
  for await (var chunk of req) body  = chunk.toString();
  console.log(body);
  res.writeHead(200, {'Content-Type' : 'text/plain'});
  res.end('hello world')
});
  • Related