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

7

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

I found some articles on the internet but nothing succinct.

    
asked by anonymous 01.01.2017 / 04:32

1 answer

7

have 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 response can be used within res.on('end', () => { .

There are libraries that simplify this, one of which is request . In this case the API may 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. 
  }
})
    
01.01.2017 / 14:23