How to request GET/POST with Node.JS?

Asked

Viewed 15,933 times

9

I need to make a request both post and get 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.

  • Here: http://stackoverflow.com/questions/5643321/how-to-make-remote-call-inside-node-js-any-curl

2 answers

11


The have a native HTTP API, http.request, that 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 within res.on('end', () => {.

There are libraries that simplify this, one of them is the request. In this case the API can be 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. 
  }
})
  • The code did not stand out from syntax, how strange. It’s javascript that?

  • @diegofm yes, it’s Javascript, weird. I’ll join the tags.

0

I think the easiest way to request is with Request https://www.npmjs.com/package/request

request('http://www.google.com', function (error, response, body) {
  console.log('error:', error); // Print the error if one occurred
  console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
  console.log('body:', body); // Print the HTML for the Google homepage.
});

In addition to this medium with callbacks you can use Promises and async/await.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.