How to make Ajax request through NodeJS to an endpoint How to make Ajax request through NodeJS to an endpoint node.js node.js

How to make Ajax request through NodeJS to an endpoint


Using request

function funcOne(input) {   var request = require('request');  request.post(someUrl, {json: true, body: input}, function(err, res, body) {      if (!err && res.statusCode === 200) {          funcTwo(body, function(err, output) {              console.log(err, output);          });      }  });}function funcTwo(input, callback) {    // process input    callback(null, input);}

Edit: Since request is now deprecated you can find alternatives here


Since request is deprecated. I recommend working with axios.

npm install axios@0.16.2

const axios = require('axios');axios.get('https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY')  .then(response => {    console.log(response.data.url);    console.log(response.data.explanation);  })  .catch(error => {    console.log(error);  });

Using the standard http library to make requests will require more effort to parse/get data. For someone who was used to making AJAX request purely in Java/JavaScript I found axios to be easy to pick up.

https://www.twilio.com/blog/2017/08/http-requests-in-node-js.html