How to make GET/POST request with Node.JS?

Question:

I need to make both a post and a get request from a REST API, I was wondering how to make the request with Node.js?

I found some articles on the internet but nothing short.

Answer:

has a native API for HTTP, http.request , which works like this:

var postData = querystring.stringify({
  'msg' : 'Hello World!'
});

var options = {
  hostname: 'www.google.com',
  port: 80,
  path: '/upload',
  method: 'POST', // <--- aqui podes escolher o método
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Content-Length': Buffer.byteLength(postData)
  }
};

var req = http.request(options, (res) => {
  res.setEncoding('utf8');
  let data = '';
  res.on('data', d => data += d);
  res.on('end', () => {
    console.log('Terminado! Data:', data);
  });
});

req.on('error', (e) => {
  console.log(`Houve um erro: ${e.message}`);
});

// aqui podes enviar data no POST
req.write(postData);
req.end();

The answer can be used inside res.on('end', () => { .

There are libraries that simplify this, one of them is request . In this case the API might look like this:

var request = require('request');
request('http://www.google.com', function (error, response, body) {
  if (!error && response.statusCode == 200) {
    console.log(body) // Aqui podes ver o HTML da página pedida. 
  }
})
Scroll to Top