Search code examples
node.jscurlecho-server

What's problem with my code. I am giving a curl post request but data is not showing in respose body of header


This code is receiving data from curl and suppose to show that data on the header body response. But it's not working. Where am I wrong???

const server = http.createServer((req , res) => {
res.writeHead(200, {'Content-type': 'text/plain'});
const { headers, method, url } = req;
let body = [];
req.on('error', (err) => {
    console.error(err);
  })
req.on('data', (chunk) => {
body.push(chunk);
})
req.on('end', () => {
    body = Buffer.concat(body).toString();
});

});


Solution

  • This should do the job if you what All together now! to be set in the response body.

    const http = require('http');
    
    const server = http.createServer((req, res) => {
        let body = [];
        req.on('error', (err) => {
            console.error(err);
        })
        req.on('data', (chunk) => {
            body.push(chunk);
        })
        req.on('end', () => {
            body = Buffer.concat(body).toString();
    
            // set response
            res.writeHead(200, { 'Content-Type': 'text/plain' });
            res.end(body);
        });
    });
    
    server.listen('3000');