0

I am a newbe in nodejs, I created a simple server with help of https://nodejs.org/en/docs/guides/getting-started-guide/ link then i want to get body and header of post request and work on it. how to i do?

const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World');
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});
hanem
  • 13
  • 5
  • Does this answer your question? [Node.js: How to send headers with form data using request module?](https://stackoverflow.com/questions/17121846/node-js-how-to-send-headers-with-form-data-using-request-module) AND [Node.js: How to send headers with form data using request module?](https://stackoverflow.com/questions/13147693/how-to-extract-request-http-headers-from-a-request-using-nodejs-connect) and maybe even: [this](https://stackoverflow.com/search?q=%5Bnode.js%5D+get+header+and+body+post+request) – Luuk Feb 26 '23 at 10:44
  • No, i want to get body and header request coming from client via node js server – hanem Feb 26 '23 at 12:17

1 Answers1

0

Using node, you can create a client script which connect to your server:

const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

http.get('http://'+hostname+':'+port, (res) => {
    console.log('Status:'+res.statusCode);
    console.log('Headers:');
    console.log(res.headers);
    console.log('Body:');

    let data = '';

    res.on('data', (chunk) => {
      data += chunk;
    });

    res.on('close', () => {
      //console.log('Retrieved all data');
      console.log(data);
    });
})

When the server is running, an answer like this is expected:

Status:200
Headers:
{
  'content-type': 'text/plain',
  date: 'Sun, 26 Feb 2023 13:52:50 GMT',
  connection: 'close',
  'content-length': '11'
}
Body
Hello World
Luuk
  • 12,245
  • 5
  • 22
  • 33