HTTP GET Request in Node.js Express












164















How can I make an HTTP request from within node/express? I need to connect to another service. I am hoping the call is async and that the callback contains the remote servers response.










share|improve this question





























    164















    How can I make an HTTP request from within node/express? I need to connect to another service. I am hoping the call is async and that the callback contains the remote servers response.










    share|improve this question



























      164












      164








      164


      77






      How can I make an HTTP request from within node/express? I need to connect to another service. I am hoping the call is async and that the callback contains the remote servers response.










      share|improve this question
















      How can I make an HTTP request from within node/express? I need to connect to another service. I am hoping the call is async and that the callback contains the remote servers response.







      javascript node.js express httprequest






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Aug 21 '12 at 11:19









      bryanmac

      34.6k97590




      34.6k97590










      asked Mar 6 '12 at 3:43









      Travis ParksTravis Parks

      3,67473669




      3,67473669
























          12 Answers
          12






          active

          oldest

          votes


















          190














          Here's code from a sample of mine. It's async and returns a JSON object. It could do any get request. Note there's more optimal ways (just a sample) - for example, instead of concatenating the chunks you put into an array and join it etc... Hopefully, it gets you started in the right direction:



          var http = require("http");
          var https = require("https");

          /**
          * getJSON: REST get request returning JSON object(s)
          * @param options: http options object
          * @param callback: callback to pass the results JSON object(s) back
          */
          exports.getJSON = function(options, onResult)
          {
          console.log("rest::getJSON");

          var port = options.port == 443 ? https : http;
          var req = port.request(options, function(res)
          {
          var output = '';
          console.log(options.host + ':' + res.statusCode);
          res.setEncoding('utf8');

          res.on('data', function (chunk) {
          output += chunk;
          });

          res.on('end', function() {
          var obj = JSON.parse(output);
          onResult(res.statusCode, obj);
          });
          });

          req.on('error', function(err) {
          //res.send('error: ' + err.message);
          });

          req.end();
          };


          It's called by creating an options objects like:



          var options = {
          host: 'somesite.com',
          port: 443,
          path: '/some/path',
          method: 'GET',
          headers: {
          'Content-Type': 'application/json'
          }
          };


          and providing a callback function.



          For example, in a service, I require the rest module above and then do this.



          rest.getJSON(options, function(statusCode, result) {
          // I could work with the result html/json here. I could also just return it
          console.log("onResult: (" + statusCode + ")" + JSON.stringify(result));
          res.statusCode = statusCode;
          res.send(result);
          });


          UPDATE:



          If you're looking for async await (linear no callback), promises, compile time support and intellisense, we create a lightweight http and rest client that fits that bill:



          Microsoft typed-rest-client






          share|improve this answer


























          • @bryanmac can you please send/add the complete sample?

            – StErMi
            Jan 17 '13 at 9:55











          • @StErMi - I updated the end of the post with a sample.

            – bryanmac
            Jan 17 '13 at 13:40






          • 2





            try request module .. it is much simpler sitepoint.com/making-http-requests-in-node-js

            – saurshaz
            Aug 24 '13 at 5:33








          • 6





            yes - request module is simple but this is lower level showing what libraries like request module is doing. If you need lower level control or http requests (showing progress on large downloads etc...), this shows how it's done.

            – bryanmac
            Aug 24 '13 at 16:50






          • 1





            @KrIsHnA - node has a querystring object: nodejs.org/api/querystring.html and url object nodejs.org/docs/latest/api/url.html

            – bryanmac
            Aug 4 '16 at 21:01



















          89














          Try using the simple http.get(options, callback) function in node.js:



          var http = require('http');
          var options = {
          host: 'www.google.com',
          path: '/index.html'
          };

          var req = http.get(options, function(res) {
          console.log('STATUS: ' + res.statusCode);
          console.log('HEADERS: ' + JSON.stringify(res.headers));

          // Buffer the body entirely for processing as a whole.
          var bodyChunks = ;
          res.on('data', function(chunk) {
          // You can process streamed parts here...
          bodyChunks.push(chunk);
          }).on('end', function() {
          var body = Buffer.concat(bodyChunks);
          console.log('BODY: ' + body);
          // ...and/or process the entire body here.
          })
          });

          req.on('error', function(e) {
          console.log('ERROR: ' + e.message);
          });


          There is also a general http.request(options, callback) function which allows you to specify the request method and other request details.






          share|improve this answer


























          • Where's the content of the server's response that the OP asked for?

            – Dan Dascalescu
            Dec 20 '13 at 13:55













          • @DanDascalescu: good point, I've updated my answer.

            – maerics
            Dec 20 '13 at 14:52











          • Thanks for the update. Looks like there's a need for an 'end' handler to concatenate the chunks then. Which basically amounts to @bryanmac's answer?

            – Dan Dascalescu
            Dec 20 '13 at 15:04











          • @DanDascalescu: ya, if you want to process the body as a whole (which is likely) then you probably want to buffer it and process on 'end'. I'll update my answer too for completeness.

            – maerics
            Dec 20 '13 at 15:30











          • sorry, i can't figure out what parameters callback is called with...how can i get body and where is the reference for parameters and properties of that parameters.

            – Muhammad Umer
            Feb 23 '15 at 0:27



















          64














          Request and Superagent are pretty good libraries to use.



          Using request:



          var request=require('request');

          request.get('https://someplace',options,function(err,res,body){
          if(err) //TODO: handle err
          if(res.statusCode !== 200 ) //etc
          //TODO Do something with response
          });





          share|improve this answer





















          • 1





            request is awesome! :)

            – Alex Zak
            Apr 21 '13 at 7:08






          • 5





            Should it be res.statusCode === 200 in second if ? )

            – Gleb Dolzikov
            Jun 27 '17 at 6:44













          • Simplest and The best :D

            – Ankit Zalani
            Oct 8 '17 at 11:28



















          30














          You can also use Requestify, a really cool and very simple HTTP client I wrote for nodeJS + it supports caching.



          Just do the following for GET method request:



          var requestify = require('requestify');

          requestify.get('http://example.com/api/resource')
          .then(function(response) {
          // Get the response body (JSON parsed or jQuery object for XMLs)
          response.getBody();
          }
          );





          share|improve this answer



















          • 2





            This is a great, no fuss library. Thank you for developing it!

            – Neeko
            Sep 14 '15 at 21:30











          • Thank you so much for this!

            – Samuel
            Oct 16 '18 at 8:08



















          7














          Unirest is the best library I've come across for making HTTP requests from Node. It's aiming at being a multiplatform framework, so learning how it works on Node will serve you well if you need to use an HTTP client on Ruby, PHP, Java, Python, Objective C, .Net or Windows 8 as well. As far as I can tell the unirest libraries are mostly backed by existing HTTP clients (e.g. on Java, the Apache HTTP client, on Node, Mikeal's Request libary) - Unirest just puts a nicer API on top.



          Here are a couple of code examples for Node.js:



          var unirest = require('unirest')

          // GET a resource
          unirest.get('http://httpbin.org/get')
          .query({'foo': 'bar'})
          .query({'stack': 'overflow'})
          .end(function(res) {
          if (res.error) {
          console.log('GET error', res.error)
          } else {
          console.log('GET response', res.body)
          }
          })

          // POST a form with an attached file
          unirest.post('http://httpbin.org/post')
          .field('foo', 'bar')
          .field('stack', 'overflow')
          .attach('myfile', 'examples.js')
          .end(function(res) {
          if (res.error) {
          console.log('POST error', res.error)
          } else {
          console.log('POST response', res.body)
          }
          })


          You can jump straight to the Node docs here






          share|improve this answer































            4














            Check out shred. It's a node HTTP client created and maintained by spire.io that handles redirects, sessions, and JSON responses. It's great for interacting with rest APIs. See this blog post for more details.






            share|improve this answer































              4














              Check out httpreq: it's a node library I created because I was frustrated there was no simple http GET or POST module out there ;-)






              share|improve this answer
























              • +1 for keeping the callback node way! function(err, res){ }

                – ygaradon
                Feb 27 '14 at 17:30



















              4














              This version is based on the initially proposed by bryanmac function which uses promises, better error handling, and is rewritten in ES6.



              let http = require("http"),
              https = require("https");

              /**
              * getJSON: REST get request returning JSON object(s)
              * @param options: http options object
              */
              exports.getJSON = function(options)
              {
              console.log('rest::getJSON');
              let reqHandler = +options.port === 443 ? https : http;

              return new Promise((resolve, reject) => {
              let req = reqHandler.request(options, (res) =>
              {
              let output = '';
              console.log('rest::', options.host + ':' + res.statusCode);
              res.setEncoding('utf8');

              res.on('data', function (chunk) {
              output += chunk;
              });

              res.on('end', () => {
              try {
              let obj = JSON.parse(output);
              // console.log('rest::', obj);
              resolve({
              statusCode: res.statusCode,
              data: obj
              });
              }
              catch(err) {
              console.error('rest::end', err);
              reject(err);
              }
              });
              });

              req.on('error', (err) => {
              console.error('rest::request', err);
              reject(err);
              });

              req.end();
              });
              };


              As a result you don't have to pass in a callback function, instead getJSON() returns a promise. In the following example the function is used inside of an ExpressJS route handler



              router.get('/:id', (req, res, next) => {
              rest.getJSON({
              host: host,
              path: `/posts/${req.params.id}`,
              method: 'GET'
              }).then(({status, data}) => {
              res.json(data);
              }, (error) => {
              next(error);
              });
              });


              On error it delegates the error to the server error handling middleware.






              share|improve this answer


























              • Yes,this example is showing how to do it inside an Express get route definition, which many posts here are lacking.

                – Micros
                Dec 21 '18 at 10:08



















              1














              If you just need to make simple get requests and don't need support for any other HTTP methods take a look at: simple-get:



              var get = require('simple-get');

              get('http://example.com', function (err, res) {
              if (err) throw err;
              console.log(res.statusCode); // 200
              res.pipe(process.stdout); // `res` is a stream
              });





              share|improve this answer































                0














                Look at request module. Reference here http://www.sitepoint.com/making-http-requests-in-node-js/






                share|improve this answer































                  0














                  Use reqclient: not designed for scripting purpose
                  like request or many other libraries. Reqclient allows in the constructor
                  specify many configurations useful when you need to reuse the same
                  configuration again and again: base URL, headers, auth options,
                  logging options, caching, etc. Also has useful features like
                  query and URL parsing, automatic query encoding and JSON parsing, etc.



                  The best way to use the library is create a module to export the object
                  pointing to the API and the necessary configurations to connect with:



                  Module client.js:



                  let RequestClient = require("reqclient").RequestClient

                  let client = new RequestClient({
                  baseUrl: "https://myapp.com/api/v1",
                  cache: true,
                  auth: {user: "admin", pass: "secret"}
                  })

                  module.exports = client


                  And in the controllers where you need to consume the API use like this:



                  let client = require('client')
                  //let router = ...

                  router.get('/dashboard', (req, res) => {
                  // Simple GET with Promise handling to https://myapp.com/api/v1/reports/clients
                  client.get("reports/clients")
                  .then(response => {
                  console.log("Report for client", response.userId) // REST responses are parsed as JSON objects
                  res.render('clients/dashboard', {title: 'Customer Report', report: response})
                  })
                  .catch(err => {
                  console.error("Ups!", err)
                  res.status(400).render('error', {error: err})
                  })
                  })

                  router.get('/orders', (req, res, next) => {
                  // GET with query (https://myapp.com/api/v1/orders?state=open&limit=10)
                  client.get({"uri": "orders", "query": {"state": "open", "limit": 10}})
                  .then(orders => {
                  res.render('clients/orders', {title: 'Customer Orders', orders: orders})
                  })
                  .catch(err => someErrorHandler(req, res, next))
                  })

                  router.delete('/orders', (req, res, next) => {
                  // DELETE with params (https://myapp.com/api/v1/orders/1234/A987)
                  client.delete({
                  "uri": "orders/{client}/{id}",
                  "params": {"client": "A987", "id": 1234}
                  })
                  .then(resp => res.status(204))
                  .catch(err => someErrorHandler(req, res, next))
                  })


                  reqclient supports many features, but it has some that are not supported by other
                  libraries: OAuth2 integration and logger integration
                  with cURL syntax, and always returns native Promise objects.






                  share|improve this answer































                    -1














                    ## you can use request module and promise in express to make any request ##
                    const promise = require('promise');
                    const requestModule = require('request');

                    const curlRequest =(requestOption) =>{
                    return new Promise((resolve, reject)=> {
                    requestModule(requestOption, (error, response, body) => {
                    try {
                    if (error) {
                    throw error;
                    }
                    if (body) {

                    try {
                    body = (body) ? JSON.parse(body) : body;
                    resolve(body);
                    }catch(error){
                    resolve(body);
                    }

                    } else {

                    throw new Error('something wrong');
                    }
                    } catch (error) {

                    reject(error);
                    }
                    })
                    })
                    };

                    const option = {
                    url : uri,
                    method : "GET",
                    headers : {

                    }
                    };


                    curlRequest(option).then((data)=>{
                    }).catch((err)=>{
                    })





                    share|improve this answer


























                    • (As it happens, it won't solve the problem. This code will listen for a request but the question is asking how to send a request)

                      – Quentin
                      Jan 30 '18 at 11:53






                    • 1





                      it is fixed, you can try it out. @Quentin

                      – izhar ahmad
                      Jan 30 '18 at 12:09













                    Your Answer






                    StackExchange.ifUsing("editor", function () {
                    StackExchange.using("externalEditor", function () {
                    StackExchange.using("snippets", function () {
                    StackExchange.snippets.init();
                    });
                    });
                    }, "code-snippets");

                    StackExchange.ready(function() {
                    var channelOptions = {
                    tags: "".split(" "),
                    id: "1"
                    };
                    initTagRenderer("".split(" "), "".split(" "), channelOptions);

                    StackExchange.using("externalEditor", function() {
                    // Have to fire editor after snippets, if snippets enabled
                    if (StackExchange.settings.snippets.snippetsEnabled) {
                    StackExchange.using("snippets", function() {
                    createEditor();
                    });
                    }
                    else {
                    createEditor();
                    }
                    });

                    function createEditor() {
                    StackExchange.prepareEditor({
                    heartbeatType: 'answer',
                    autoActivateHeartbeat: false,
                    convertImagesToLinks: true,
                    noModals: true,
                    showLowRepImageUploadWarning: true,
                    reputationToPostImages: 10,
                    bindNavPrevention: true,
                    postfix: "",
                    imageUploader: {
                    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                    allowUrls: true
                    },
                    onDemand: true,
                    discardSelector: ".discard-answer"
                    ,immediatelyShowMarkdownHelp:true
                    });


                    }
                    });














                    draft saved

                    draft discarded


















                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f9577611%2fhttp-get-request-in-node-js-express%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown

























                    12 Answers
                    12






                    active

                    oldest

                    votes








                    12 Answers
                    12






                    active

                    oldest

                    votes









                    active

                    oldest

                    votes






                    active

                    oldest

                    votes









                    190














                    Here's code from a sample of mine. It's async and returns a JSON object. It could do any get request. Note there's more optimal ways (just a sample) - for example, instead of concatenating the chunks you put into an array and join it etc... Hopefully, it gets you started in the right direction:



                    var http = require("http");
                    var https = require("https");

                    /**
                    * getJSON: REST get request returning JSON object(s)
                    * @param options: http options object
                    * @param callback: callback to pass the results JSON object(s) back
                    */
                    exports.getJSON = function(options, onResult)
                    {
                    console.log("rest::getJSON");

                    var port = options.port == 443 ? https : http;
                    var req = port.request(options, function(res)
                    {
                    var output = '';
                    console.log(options.host + ':' + res.statusCode);
                    res.setEncoding('utf8');

                    res.on('data', function (chunk) {
                    output += chunk;
                    });

                    res.on('end', function() {
                    var obj = JSON.parse(output);
                    onResult(res.statusCode, obj);
                    });
                    });

                    req.on('error', function(err) {
                    //res.send('error: ' + err.message);
                    });

                    req.end();
                    };


                    It's called by creating an options objects like:



                    var options = {
                    host: 'somesite.com',
                    port: 443,
                    path: '/some/path',
                    method: 'GET',
                    headers: {
                    'Content-Type': 'application/json'
                    }
                    };


                    and providing a callback function.



                    For example, in a service, I require the rest module above and then do this.



                    rest.getJSON(options, function(statusCode, result) {
                    // I could work with the result html/json here. I could also just return it
                    console.log("onResult: (" + statusCode + ")" + JSON.stringify(result));
                    res.statusCode = statusCode;
                    res.send(result);
                    });


                    UPDATE:



                    If you're looking for async await (linear no callback), promises, compile time support and intellisense, we create a lightweight http and rest client that fits that bill:



                    Microsoft typed-rest-client






                    share|improve this answer


























                    • @bryanmac can you please send/add the complete sample?

                      – StErMi
                      Jan 17 '13 at 9:55











                    • @StErMi - I updated the end of the post with a sample.

                      – bryanmac
                      Jan 17 '13 at 13:40






                    • 2





                      try request module .. it is much simpler sitepoint.com/making-http-requests-in-node-js

                      – saurshaz
                      Aug 24 '13 at 5:33








                    • 6





                      yes - request module is simple but this is lower level showing what libraries like request module is doing. If you need lower level control or http requests (showing progress on large downloads etc...), this shows how it's done.

                      – bryanmac
                      Aug 24 '13 at 16:50






                    • 1





                      @KrIsHnA - node has a querystring object: nodejs.org/api/querystring.html and url object nodejs.org/docs/latest/api/url.html

                      – bryanmac
                      Aug 4 '16 at 21:01
















                    190














                    Here's code from a sample of mine. It's async and returns a JSON object. It could do any get request. Note there's more optimal ways (just a sample) - for example, instead of concatenating the chunks you put into an array and join it etc... Hopefully, it gets you started in the right direction:



                    var http = require("http");
                    var https = require("https");

                    /**
                    * getJSON: REST get request returning JSON object(s)
                    * @param options: http options object
                    * @param callback: callback to pass the results JSON object(s) back
                    */
                    exports.getJSON = function(options, onResult)
                    {
                    console.log("rest::getJSON");

                    var port = options.port == 443 ? https : http;
                    var req = port.request(options, function(res)
                    {
                    var output = '';
                    console.log(options.host + ':' + res.statusCode);
                    res.setEncoding('utf8');

                    res.on('data', function (chunk) {
                    output += chunk;
                    });

                    res.on('end', function() {
                    var obj = JSON.parse(output);
                    onResult(res.statusCode, obj);
                    });
                    });

                    req.on('error', function(err) {
                    //res.send('error: ' + err.message);
                    });

                    req.end();
                    };


                    It's called by creating an options objects like:



                    var options = {
                    host: 'somesite.com',
                    port: 443,
                    path: '/some/path',
                    method: 'GET',
                    headers: {
                    'Content-Type': 'application/json'
                    }
                    };


                    and providing a callback function.



                    For example, in a service, I require the rest module above and then do this.



                    rest.getJSON(options, function(statusCode, result) {
                    // I could work with the result html/json here. I could also just return it
                    console.log("onResult: (" + statusCode + ")" + JSON.stringify(result));
                    res.statusCode = statusCode;
                    res.send(result);
                    });


                    UPDATE:



                    If you're looking for async await (linear no callback), promises, compile time support and intellisense, we create a lightweight http and rest client that fits that bill:



                    Microsoft typed-rest-client






                    share|improve this answer


























                    • @bryanmac can you please send/add the complete sample?

                      – StErMi
                      Jan 17 '13 at 9:55











                    • @StErMi - I updated the end of the post with a sample.

                      – bryanmac
                      Jan 17 '13 at 13:40






                    • 2





                      try request module .. it is much simpler sitepoint.com/making-http-requests-in-node-js

                      – saurshaz
                      Aug 24 '13 at 5:33








                    • 6





                      yes - request module is simple but this is lower level showing what libraries like request module is doing. If you need lower level control or http requests (showing progress on large downloads etc...), this shows how it's done.

                      – bryanmac
                      Aug 24 '13 at 16:50






                    • 1





                      @KrIsHnA - node has a querystring object: nodejs.org/api/querystring.html and url object nodejs.org/docs/latest/api/url.html

                      – bryanmac
                      Aug 4 '16 at 21:01














                    190












                    190








                    190







                    Here's code from a sample of mine. It's async and returns a JSON object. It could do any get request. Note there's more optimal ways (just a sample) - for example, instead of concatenating the chunks you put into an array and join it etc... Hopefully, it gets you started in the right direction:



                    var http = require("http");
                    var https = require("https");

                    /**
                    * getJSON: REST get request returning JSON object(s)
                    * @param options: http options object
                    * @param callback: callback to pass the results JSON object(s) back
                    */
                    exports.getJSON = function(options, onResult)
                    {
                    console.log("rest::getJSON");

                    var port = options.port == 443 ? https : http;
                    var req = port.request(options, function(res)
                    {
                    var output = '';
                    console.log(options.host + ':' + res.statusCode);
                    res.setEncoding('utf8');

                    res.on('data', function (chunk) {
                    output += chunk;
                    });

                    res.on('end', function() {
                    var obj = JSON.parse(output);
                    onResult(res.statusCode, obj);
                    });
                    });

                    req.on('error', function(err) {
                    //res.send('error: ' + err.message);
                    });

                    req.end();
                    };


                    It's called by creating an options objects like:



                    var options = {
                    host: 'somesite.com',
                    port: 443,
                    path: '/some/path',
                    method: 'GET',
                    headers: {
                    'Content-Type': 'application/json'
                    }
                    };


                    and providing a callback function.



                    For example, in a service, I require the rest module above and then do this.



                    rest.getJSON(options, function(statusCode, result) {
                    // I could work with the result html/json here. I could also just return it
                    console.log("onResult: (" + statusCode + ")" + JSON.stringify(result));
                    res.statusCode = statusCode;
                    res.send(result);
                    });


                    UPDATE:



                    If you're looking for async await (linear no callback), promises, compile time support and intellisense, we create a lightweight http and rest client that fits that bill:



                    Microsoft typed-rest-client






                    share|improve this answer















                    Here's code from a sample of mine. It's async and returns a JSON object. It could do any get request. Note there's more optimal ways (just a sample) - for example, instead of concatenating the chunks you put into an array and join it etc... Hopefully, it gets you started in the right direction:



                    var http = require("http");
                    var https = require("https");

                    /**
                    * getJSON: REST get request returning JSON object(s)
                    * @param options: http options object
                    * @param callback: callback to pass the results JSON object(s) back
                    */
                    exports.getJSON = function(options, onResult)
                    {
                    console.log("rest::getJSON");

                    var port = options.port == 443 ? https : http;
                    var req = port.request(options, function(res)
                    {
                    var output = '';
                    console.log(options.host + ':' + res.statusCode);
                    res.setEncoding('utf8');

                    res.on('data', function (chunk) {
                    output += chunk;
                    });

                    res.on('end', function() {
                    var obj = JSON.parse(output);
                    onResult(res.statusCode, obj);
                    });
                    });

                    req.on('error', function(err) {
                    //res.send('error: ' + err.message);
                    });

                    req.end();
                    };


                    It's called by creating an options objects like:



                    var options = {
                    host: 'somesite.com',
                    port: 443,
                    path: '/some/path',
                    method: 'GET',
                    headers: {
                    'Content-Type': 'application/json'
                    }
                    };


                    and providing a callback function.



                    For example, in a service, I require the rest module above and then do this.



                    rest.getJSON(options, function(statusCode, result) {
                    // I could work with the result html/json here. I could also just return it
                    console.log("onResult: (" + statusCode + ")" + JSON.stringify(result));
                    res.statusCode = statusCode;
                    res.send(result);
                    });


                    UPDATE:



                    If you're looking for async await (linear no callback), promises, compile time support and intellisense, we create a lightweight http and rest client that fits that bill:



                    Microsoft typed-rest-client







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Nov 21 '17 at 11:23









                    Kondal

                    1,22521332




                    1,22521332










                    answered Mar 6 '12 at 3:50









                    bryanmacbryanmac

                    34.6k97590




                    34.6k97590













                    • @bryanmac can you please send/add the complete sample?

                      – StErMi
                      Jan 17 '13 at 9:55











                    • @StErMi - I updated the end of the post with a sample.

                      – bryanmac
                      Jan 17 '13 at 13:40






                    • 2





                      try request module .. it is much simpler sitepoint.com/making-http-requests-in-node-js

                      – saurshaz
                      Aug 24 '13 at 5:33








                    • 6





                      yes - request module is simple but this is lower level showing what libraries like request module is doing. If you need lower level control or http requests (showing progress on large downloads etc...), this shows how it's done.

                      – bryanmac
                      Aug 24 '13 at 16:50






                    • 1





                      @KrIsHnA - node has a querystring object: nodejs.org/api/querystring.html and url object nodejs.org/docs/latest/api/url.html

                      – bryanmac
                      Aug 4 '16 at 21:01



















                    • @bryanmac can you please send/add the complete sample?

                      – StErMi
                      Jan 17 '13 at 9:55











                    • @StErMi - I updated the end of the post with a sample.

                      – bryanmac
                      Jan 17 '13 at 13:40






                    • 2





                      try request module .. it is much simpler sitepoint.com/making-http-requests-in-node-js

                      – saurshaz
                      Aug 24 '13 at 5:33








                    • 6





                      yes - request module is simple but this is lower level showing what libraries like request module is doing. If you need lower level control or http requests (showing progress on large downloads etc...), this shows how it's done.

                      – bryanmac
                      Aug 24 '13 at 16:50






                    • 1





                      @KrIsHnA - node has a querystring object: nodejs.org/api/querystring.html and url object nodejs.org/docs/latest/api/url.html

                      – bryanmac
                      Aug 4 '16 at 21:01

















                    @bryanmac can you please send/add the complete sample?

                    – StErMi
                    Jan 17 '13 at 9:55





                    @bryanmac can you please send/add the complete sample?

                    – StErMi
                    Jan 17 '13 at 9:55













                    @StErMi - I updated the end of the post with a sample.

                    – bryanmac
                    Jan 17 '13 at 13:40





                    @StErMi - I updated the end of the post with a sample.

                    – bryanmac
                    Jan 17 '13 at 13:40




                    2




                    2





                    try request module .. it is much simpler sitepoint.com/making-http-requests-in-node-js

                    – saurshaz
                    Aug 24 '13 at 5:33







                    try request module .. it is much simpler sitepoint.com/making-http-requests-in-node-js

                    – saurshaz
                    Aug 24 '13 at 5:33






                    6




                    6





                    yes - request module is simple but this is lower level showing what libraries like request module is doing. If you need lower level control or http requests (showing progress on large downloads etc...), this shows how it's done.

                    – bryanmac
                    Aug 24 '13 at 16:50





                    yes - request module is simple but this is lower level showing what libraries like request module is doing. If you need lower level control or http requests (showing progress on large downloads etc...), this shows how it's done.

                    – bryanmac
                    Aug 24 '13 at 16:50




                    1




                    1





                    @KrIsHnA - node has a querystring object: nodejs.org/api/querystring.html and url object nodejs.org/docs/latest/api/url.html

                    – bryanmac
                    Aug 4 '16 at 21:01





                    @KrIsHnA - node has a querystring object: nodejs.org/api/querystring.html and url object nodejs.org/docs/latest/api/url.html

                    – bryanmac
                    Aug 4 '16 at 21:01













                    89














                    Try using the simple http.get(options, callback) function in node.js:



                    var http = require('http');
                    var options = {
                    host: 'www.google.com',
                    path: '/index.html'
                    };

                    var req = http.get(options, function(res) {
                    console.log('STATUS: ' + res.statusCode);
                    console.log('HEADERS: ' + JSON.stringify(res.headers));

                    // Buffer the body entirely for processing as a whole.
                    var bodyChunks = ;
                    res.on('data', function(chunk) {
                    // You can process streamed parts here...
                    bodyChunks.push(chunk);
                    }).on('end', function() {
                    var body = Buffer.concat(bodyChunks);
                    console.log('BODY: ' + body);
                    // ...and/or process the entire body here.
                    })
                    });

                    req.on('error', function(e) {
                    console.log('ERROR: ' + e.message);
                    });


                    There is also a general http.request(options, callback) function which allows you to specify the request method and other request details.






                    share|improve this answer


























                    • Where's the content of the server's response that the OP asked for?

                      – Dan Dascalescu
                      Dec 20 '13 at 13:55













                    • @DanDascalescu: good point, I've updated my answer.

                      – maerics
                      Dec 20 '13 at 14:52











                    • Thanks for the update. Looks like there's a need for an 'end' handler to concatenate the chunks then. Which basically amounts to @bryanmac's answer?

                      – Dan Dascalescu
                      Dec 20 '13 at 15:04











                    • @DanDascalescu: ya, if you want to process the body as a whole (which is likely) then you probably want to buffer it and process on 'end'. I'll update my answer too for completeness.

                      – maerics
                      Dec 20 '13 at 15:30











                    • sorry, i can't figure out what parameters callback is called with...how can i get body and where is the reference for parameters and properties of that parameters.

                      – Muhammad Umer
                      Feb 23 '15 at 0:27
















                    89














                    Try using the simple http.get(options, callback) function in node.js:



                    var http = require('http');
                    var options = {
                    host: 'www.google.com',
                    path: '/index.html'
                    };

                    var req = http.get(options, function(res) {
                    console.log('STATUS: ' + res.statusCode);
                    console.log('HEADERS: ' + JSON.stringify(res.headers));

                    // Buffer the body entirely for processing as a whole.
                    var bodyChunks = ;
                    res.on('data', function(chunk) {
                    // You can process streamed parts here...
                    bodyChunks.push(chunk);
                    }).on('end', function() {
                    var body = Buffer.concat(bodyChunks);
                    console.log('BODY: ' + body);
                    // ...and/or process the entire body here.
                    })
                    });

                    req.on('error', function(e) {
                    console.log('ERROR: ' + e.message);
                    });


                    There is also a general http.request(options, callback) function which allows you to specify the request method and other request details.






                    share|improve this answer


























                    • Where's the content of the server's response that the OP asked for?

                      – Dan Dascalescu
                      Dec 20 '13 at 13:55













                    • @DanDascalescu: good point, I've updated my answer.

                      – maerics
                      Dec 20 '13 at 14:52











                    • Thanks for the update. Looks like there's a need for an 'end' handler to concatenate the chunks then. Which basically amounts to @bryanmac's answer?

                      – Dan Dascalescu
                      Dec 20 '13 at 15:04











                    • @DanDascalescu: ya, if you want to process the body as a whole (which is likely) then you probably want to buffer it and process on 'end'. I'll update my answer too for completeness.

                      – maerics
                      Dec 20 '13 at 15:30











                    • sorry, i can't figure out what parameters callback is called with...how can i get body and where is the reference for parameters and properties of that parameters.

                      – Muhammad Umer
                      Feb 23 '15 at 0:27














                    89












                    89








                    89







                    Try using the simple http.get(options, callback) function in node.js:



                    var http = require('http');
                    var options = {
                    host: 'www.google.com',
                    path: '/index.html'
                    };

                    var req = http.get(options, function(res) {
                    console.log('STATUS: ' + res.statusCode);
                    console.log('HEADERS: ' + JSON.stringify(res.headers));

                    // Buffer the body entirely for processing as a whole.
                    var bodyChunks = ;
                    res.on('data', function(chunk) {
                    // You can process streamed parts here...
                    bodyChunks.push(chunk);
                    }).on('end', function() {
                    var body = Buffer.concat(bodyChunks);
                    console.log('BODY: ' + body);
                    // ...and/or process the entire body here.
                    })
                    });

                    req.on('error', function(e) {
                    console.log('ERROR: ' + e.message);
                    });


                    There is also a general http.request(options, callback) function which allows you to specify the request method and other request details.






                    share|improve this answer















                    Try using the simple http.get(options, callback) function in node.js:



                    var http = require('http');
                    var options = {
                    host: 'www.google.com',
                    path: '/index.html'
                    };

                    var req = http.get(options, function(res) {
                    console.log('STATUS: ' + res.statusCode);
                    console.log('HEADERS: ' + JSON.stringify(res.headers));

                    // Buffer the body entirely for processing as a whole.
                    var bodyChunks = ;
                    res.on('data', function(chunk) {
                    // You can process streamed parts here...
                    bodyChunks.push(chunk);
                    }).on('end', function() {
                    var body = Buffer.concat(bodyChunks);
                    console.log('BODY: ' + body);
                    // ...and/or process the entire body here.
                    })
                    });

                    req.on('error', function(e) {
                    console.log('ERROR: ' + e.message);
                    });


                    There is also a general http.request(options, callback) function which allows you to specify the request method and other request details.







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Dec 21 '13 at 23:17









                    think123

                    10.4k2380145




                    10.4k2380145










                    answered Mar 6 '12 at 5:32









                    maericsmaerics

                    104k29201249




                    104k29201249













                    • Where's the content of the server's response that the OP asked for?

                      – Dan Dascalescu
                      Dec 20 '13 at 13:55













                    • @DanDascalescu: good point, I've updated my answer.

                      – maerics
                      Dec 20 '13 at 14:52











                    • Thanks for the update. Looks like there's a need for an 'end' handler to concatenate the chunks then. Which basically amounts to @bryanmac's answer?

                      – Dan Dascalescu
                      Dec 20 '13 at 15:04











                    • @DanDascalescu: ya, if you want to process the body as a whole (which is likely) then you probably want to buffer it and process on 'end'. I'll update my answer too for completeness.

                      – maerics
                      Dec 20 '13 at 15:30











                    • sorry, i can't figure out what parameters callback is called with...how can i get body and where is the reference for parameters and properties of that parameters.

                      – Muhammad Umer
                      Feb 23 '15 at 0:27



















                    • Where's the content of the server's response that the OP asked for?

                      – Dan Dascalescu
                      Dec 20 '13 at 13:55













                    • @DanDascalescu: good point, I've updated my answer.

                      – maerics
                      Dec 20 '13 at 14:52











                    • Thanks for the update. Looks like there's a need for an 'end' handler to concatenate the chunks then. Which basically amounts to @bryanmac's answer?

                      – Dan Dascalescu
                      Dec 20 '13 at 15:04











                    • @DanDascalescu: ya, if you want to process the body as a whole (which is likely) then you probably want to buffer it and process on 'end'. I'll update my answer too for completeness.

                      – maerics
                      Dec 20 '13 at 15:30











                    • sorry, i can't figure out what parameters callback is called with...how can i get body and where is the reference for parameters and properties of that parameters.

                      – Muhammad Umer
                      Feb 23 '15 at 0:27

















                    Where's the content of the server's response that the OP asked for?

                    – Dan Dascalescu
                    Dec 20 '13 at 13:55







                    Where's the content of the server's response that the OP asked for?

                    – Dan Dascalescu
                    Dec 20 '13 at 13:55















                    @DanDascalescu: good point, I've updated my answer.

                    – maerics
                    Dec 20 '13 at 14:52





                    @DanDascalescu: good point, I've updated my answer.

                    – maerics
                    Dec 20 '13 at 14:52













                    Thanks for the update. Looks like there's a need for an 'end' handler to concatenate the chunks then. Which basically amounts to @bryanmac's answer?

                    – Dan Dascalescu
                    Dec 20 '13 at 15:04





                    Thanks for the update. Looks like there's a need for an 'end' handler to concatenate the chunks then. Which basically amounts to @bryanmac's answer?

                    – Dan Dascalescu
                    Dec 20 '13 at 15:04













                    @DanDascalescu: ya, if you want to process the body as a whole (which is likely) then you probably want to buffer it and process on 'end'. I'll update my answer too for completeness.

                    – maerics
                    Dec 20 '13 at 15:30





                    @DanDascalescu: ya, if you want to process the body as a whole (which is likely) then you probably want to buffer it and process on 'end'. I'll update my answer too for completeness.

                    – maerics
                    Dec 20 '13 at 15:30













                    sorry, i can't figure out what parameters callback is called with...how can i get body and where is the reference for parameters and properties of that parameters.

                    – Muhammad Umer
                    Feb 23 '15 at 0:27





                    sorry, i can't figure out what parameters callback is called with...how can i get body and where is the reference for parameters and properties of that parameters.

                    – Muhammad Umer
                    Feb 23 '15 at 0:27











                    64














                    Request and Superagent are pretty good libraries to use.



                    Using request:



                    var request=require('request');

                    request.get('https://someplace',options,function(err,res,body){
                    if(err) //TODO: handle err
                    if(res.statusCode !== 200 ) //etc
                    //TODO Do something with response
                    });





                    share|improve this answer





















                    • 1





                      request is awesome! :)

                      – Alex Zak
                      Apr 21 '13 at 7:08






                    • 5





                      Should it be res.statusCode === 200 in second if ? )

                      – Gleb Dolzikov
                      Jun 27 '17 at 6:44













                    • Simplest and The best :D

                      – Ankit Zalani
                      Oct 8 '17 at 11:28
















                    64














                    Request and Superagent are pretty good libraries to use.



                    Using request:



                    var request=require('request');

                    request.get('https://someplace',options,function(err,res,body){
                    if(err) //TODO: handle err
                    if(res.statusCode !== 200 ) //etc
                    //TODO Do something with response
                    });





                    share|improve this answer





















                    • 1





                      request is awesome! :)

                      – Alex Zak
                      Apr 21 '13 at 7:08






                    • 5





                      Should it be res.statusCode === 200 in second if ? )

                      – Gleb Dolzikov
                      Jun 27 '17 at 6:44













                    • Simplest and The best :D

                      – Ankit Zalani
                      Oct 8 '17 at 11:28














                    64












                    64








                    64







                    Request and Superagent are pretty good libraries to use.



                    Using request:



                    var request=require('request');

                    request.get('https://someplace',options,function(err,res,body){
                    if(err) //TODO: handle err
                    if(res.statusCode !== 200 ) //etc
                    //TODO Do something with response
                    });





                    share|improve this answer















                    Request and Superagent are pretty good libraries to use.



                    Using request:



                    var request=require('request');

                    request.get('https://someplace',options,function(err,res,body){
                    if(err) //TODO: handle err
                    if(res.statusCode !== 200 ) //etc
                    //TODO Do something with response
                    });






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Dec 3 '16 at 19:05









                    Eugenio Pace

                    12.1k12741




                    12.1k12741










                    answered Mar 6 '12 at 5:21









                    staackuser2staackuser2

                    8,85833639




                    8,85833639








                    • 1





                      request is awesome! :)

                      – Alex Zak
                      Apr 21 '13 at 7:08






                    • 5





                      Should it be res.statusCode === 200 in second if ? )

                      – Gleb Dolzikov
                      Jun 27 '17 at 6:44













                    • Simplest and The best :D

                      – Ankit Zalani
                      Oct 8 '17 at 11:28














                    • 1





                      request is awesome! :)

                      – Alex Zak
                      Apr 21 '13 at 7:08






                    • 5





                      Should it be res.statusCode === 200 in second if ? )

                      – Gleb Dolzikov
                      Jun 27 '17 at 6:44













                    • Simplest and The best :D

                      – Ankit Zalani
                      Oct 8 '17 at 11:28








                    1




                    1





                    request is awesome! :)

                    – Alex Zak
                    Apr 21 '13 at 7:08





                    request is awesome! :)

                    – Alex Zak
                    Apr 21 '13 at 7:08




                    5




                    5





                    Should it be res.statusCode === 200 in second if ? )

                    – Gleb Dolzikov
                    Jun 27 '17 at 6:44







                    Should it be res.statusCode === 200 in second if ? )

                    – Gleb Dolzikov
                    Jun 27 '17 at 6:44















                    Simplest and The best :D

                    – Ankit Zalani
                    Oct 8 '17 at 11:28





                    Simplest and The best :D

                    – Ankit Zalani
                    Oct 8 '17 at 11:28











                    30














                    You can also use Requestify, a really cool and very simple HTTP client I wrote for nodeJS + it supports caching.



                    Just do the following for GET method request:



                    var requestify = require('requestify');

                    requestify.get('http://example.com/api/resource')
                    .then(function(response) {
                    // Get the response body (JSON parsed or jQuery object for XMLs)
                    response.getBody();
                    }
                    );





                    share|improve this answer



















                    • 2





                      This is a great, no fuss library. Thank you for developing it!

                      – Neeko
                      Sep 14 '15 at 21:30











                    • Thank you so much for this!

                      – Samuel
                      Oct 16 '18 at 8:08
















                    30














                    You can also use Requestify, a really cool and very simple HTTP client I wrote for nodeJS + it supports caching.



                    Just do the following for GET method request:



                    var requestify = require('requestify');

                    requestify.get('http://example.com/api/resource')
                    .then(function(response) {
                    // Get the response body (JSON parsed or jQuery object for XMLs)
                    response.getBody();
                    }
                    );





                    share|improve this answer



















                    • 2





                      This is a great, no fuss library. Thank you for developing it!

                      – Neeko
                      Sep 14 '15 at 21:30











                    • Thank you so much for this!

                      – Samuel
                      Oct 16 '18 at 8:08














                    30












                    30








                    30







                    You can also use Requestify, a really cool and very simple HTTP client I wrote for nodeJS + it supports caching.



                    Just do the following for GET method request:



                    var requestify = require('requestify');

                    requestify.get('http://example.com/api/resource')
                    .then(function(response) {
                    // Get the response body (JSON parsed or jQuery object for XMLs)
                    response.getBody();
                    }
                    );





                    share|improve this answer













                    You can also use Requestify, a really cool and very simple HTTP client I wrote for nodeJS + it supports caching.



                    Just do the following for GET method request:



                    var requestify = require('requestify');

                    requestify.get('http://example.com/api/resource')
                    .then(function(response) {
                    // Get the response body (JSON parsed or jQuery object for XMLs)
                    response.getBody();
                    }
                    );






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Aug 3 '13 at 18:50









                    ranm8ranm8

                    941810




                    941810








                    • 2





                      This is a great, no fuss library. Thank you for developing it!

                      – Neeko
                      Sep 14 '15 at 21:30











                    • Thank you so much for this!

                      – Samuel
                      Oct 16 '18 at 8:08














                    • 2





                      This is a great, no fuss library. Thank you for developing it!

                      – Neeko
                      Sep 14 '15 at 21:30











                    • Thank you so much for this!

                      – Samuel
                      Oct 16 '18 at 8:08








                    2




                    2





                    This is a great, no fuss library. Thank you for developing it!

                    – Neeko
                    Sep 14 '15 at 21:30





                    This is a great, no fuss library. Thank you for developing it!

                    – Neeko
                    Sep 14 '15 at 21:30













                    Thank you so much for this!

                    – Samuel
                    Oct 16 '18 at 8:08





                    Thank you so much for this!

                    – Samuel
                    Oct 16 '18 at 8:08











                    7














                    Unirest is the best library I've come across for making HTTP requests from Node. It's aiming at being a multiplatform framework, so learning how it works on Node will serve you well if you need to use an HTTP client on Ruby, PHP, Java, Python, Objective C, .Net or Windows 8 as well. As far as I can tell the unirest libraries are mostly backed by existing HTTP clients (e.g. on Java, the Apache HTTP client, on Node, Mikeal's Request libary) - Unirest just puts a nicer API on top.



                    Here are a couple of code examples for Node.js:



                    var unirest = require('unirest')

                    // GET a resource
                    unirest.get('http://httpbin.org/get')
                    .query({'foo': 'bar'})
                    .query({'stack': 'overflow'})
                    .end(function(res) {
                    if (res.error) {
                    console.log('GET error', res.error)
                    } else {
                    console.log('GET response', res.body)
                    }
                    })

                    // POST a form with an attached file
                    unirest.post('http://httpbin.org/post')
                    .field('foo', 'bar')
                    .field('stack', 'overflow')
                    .attach('myfile', 'examples.js')
                    .end(function(res) {
                    if (res.error) {
                    console.log('POST error', res.error)
                    } else {
                    console.log('POST response', res.body)
                    }
                    })


                    You can jump straight to the Node docs here






                    share|improve this answer




























                      7














                      Unirest is the best library I've come across for making HTTP requests from Node. It's aiming at being a multiplatform framework, so learning how it works on Node will serve you well if you need to use an HTTP client on Ruby, PHP, Java, Python, Objective C, .Net or Windows 8 as well. As far as I can tell the unirest libraries are mostly backed by existing HTTP clients (e.g. on Java, the Apache HTTP client, on Node, Mikeal's Request libary) - Unirest just puts a nicer API on top.



                      Here are a couple of code examples for Node.js:



                      var unirest = require('unirest')

                      // GET a resource
                      unirest.get('http://httpbin.org/get')
                      .query({'foo': 'bar'})
                      .query({'stack': 'overflow'})
                      .end(function(res) {
                      if (res.error) {
                      console.log('GET error', res.error)
                      } else {
                      console.log('GET response', res.body)
                      }
                      })

                      // POST a form with an attached file
                      unirest.post('http://httpbin.org/post')
                      .field('foo', 'bar')
                      .field('stack', 'overflow')
                      .attach('myfile', 'examples.js')
                      .end(function(res) {
                      if (res.error) {
                      console.log('POST error', res.error)
                      } else {
                      console.log('POST response', res.body)
                      }
                      })


                      You can jump straight to the Node docs here






                      share|improve this answer


























                        7












                        7








                        7







                        Unirest is the best library I've come across for making HTTP requests from Node. It's aiming at being a multiplatform framework, so learning how it works on Node will serve you well if you need to use an HTTP client on Ruby, PHP, Java, Python, Objective C, .Net or Windows 8 as well. As far as I can tell the unirest libraries are mostly backed by existing HTTP clients (e.g. on Java, the Apache HTTP client, on Node, Mikeal's Request libary) - Unirest just puts a nicer API on top.



                        Here are a couple of code examples for Node.js:



                        var unirest = require('unirest')

                        // GET a resource
                        unirest.get('http://httpbin.org/get')
                        .query({'foo': 'bar'})
                        .query({'stack': 'overflow'})
                        .end(function(res) {
                        if (res.error) {
                        console.log('GET error', res.error)
                        } else {
                        console.log('GET response', res.body)
                        }
                        })

                        // POST a form with an attached file
                        unirest.post('http://httpbin.org/post')
                        .field('foo', 'bar')
                        .field('stack', 'overflow')
                        .attach('myfile', 'examples.js')
                        .end(function(res) {
                        if (res.error) {
                        console.log('POST error', res.error)
                        } else {
                        console.log('POST response', res.body)
                        }
                        })


                        You can jump straight to the Node docs here






                        share|improve this answer













                        Unirest is the best library I've come across for making HTTP requests from Node. It's aiming at being a multiplatform framework, so learning how it works on Node will serve you well if you need to use an HTTP client on Ruby, PHP, Java, Python, Objective C, .Net or Windows 8 as well. As far as I can tell the unirest libraries are mostly backed by existing HTTP clients (e.g. on Java, the Apache HTTP client, on Node, Mikeal's Request libary) - Unirest just puts a nicer API on top.



                        Here are a couple of code examples for Node.js:



                        var unirest = require('unirest')

                        // GET a resource
                        unirest.get('http://httpbin.org/get')
                        .query({'foo': 'bar'})
                        .query({'stack': 'overflow'})
                        .end(function(res) {
                        if (res.error) {
                        console.log('GET error', res.error)
                        } else {
                        console.log('GET response', res.body)
                        }
                        })

                        // POST a form with an attached file
                        unirest.post('http://httpbin.org/post')
                        .field('foo', 'bar')
                        .field('stack', 'overflow')
                        .attach('myfile', 'examples.js')
                        .end(function(res) {
                        if (res.error) {
                        console.log('POST error', res.error)
                        } else {
                        console.log('POST response', res.body)
                        }
                        })


                        You can jump straight to the Node docs here







                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered May 12 '14 at 19:06









                        Brian BeckettBrian Beckett

                        2,90562450




                        2,90562450























                            4














                            Check out shred. It's a node HTTP client created and maintained by spire.io that handles redirects, sessions, and JSON responses. It's great for interacting with rest APIs. See this blog post for more details.






                            share|improve this answer




























                              4














                              Check out shred. It's a node HTTP client created and maintained by spire.io that handles redirects, sessions, and JSON responses. It's great for interacting with rest APIs. See this blog post for more details.






                              share|improve this answer


























                                4












                                4








                                4







                                Check out shred. It's a node HTTP client created and maintained by spire.io that handles redirects, sessions, and JSON responses. It's great for interacting with rest APIs. See this blog post for more details.






                                share|improve this answer













                                Check out shred. It's a node HTTP client created and maintained by spire.io that handles redirects, sessions, and JSON responses. It's great for interacting with rest APIs. See this blog post for more details.







                                share|improve this answer












                                share|improve this answer



                                share|improve this answer










                                answered Mar 6 '12 at 5:01









                                Jonathan McIntireJonathan McIntire

                                2,4871825




                                2,4871825























                                    4














                                    Check out httpreq: it's a node library I created because I was frustrated there was no simple http GET or POST module out there ;-)






                                    share|improve this answer
























                                    • +1 for keeping the callback node way! function(err, res){ }

                                      – ygaradon
                                      Feb 27 '14 at 17:30
















                                    4














                                    Check out httpreq: it's a node library I created because I was frustrated there was no simple http GET or POST module out there ;-)






                                    share|improve this answer
























                                    • +1 for keeping the callback node way! function(err, res){ }

                                      – ygaradon
                                      Feb 27 '14 at 17:30














                                    4












                                    4








                                    4







                                    Check out httpreq: it's a node library I created because I was frustrated there was no simple http GET or POST module out there ;-)






                                    share|improve this answer













                                    Check out httpreq: it's a node library I created because I was frustrated there was no simple http GET or POST module out there ;-)







                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Mar 9 '13 at 17:11









                                    SamSam

                                    2,14711827




                                    2,14711827













                                    • +1 for keeping the callback node way! function(err, res){ }

                                      – ygaradon
                                      Feb 27 '14 at 17:30



















                                    • +1 for keeping the callback node way! function(err, res){ }

                                      – ygaradon
                                      Feb 27 '14 at 17:30

















                                    +1 for keeping the callback node way! function(err, res){ }

                                    – ygaradon
                                    Feb 27 '14 at 17:30





                                    +1 for keeping the callback node way! function(err, res){ }

                                    – ygaradon
                                    Feb 27 '14 at 17:30











                                    4














                                    This version is based on the initially proposed by bryanmac function which uses promises, better error handling, and is rewritten in ES6.



                                    let http = require("http"),
                                    https = require("https");

                                    /**
                                    * getJSON: REST get request returning JSON object(s)
                                    * @param options: http options object
                                    */
                                    exports.getJSON = function(options)
                                    {
                                    console.log('rest::getJSON');
                                    let reqHandler = +options.port === 443 ? https : http;

                                    return new Promise((resolve, reject) => {
                                    let req = reqHandler.request(options, (res) =>
                                    {
                                    let output = '';
                                    console.log('rest::', options.host + ':' + res.statusCode);
                                    res.setEncoding('utf8');

                                    res.on('data', function (chunk) {
                                    output += chunk;
                                    });

                                    res.on('end', () => {
                                    try {
                                    let obj = JSON.parse(output);
                                    // console.log('rest::', obj);
                                    resolve({
                                    statusCode: res.statusCode,
                                    data: obj
                                    });
                                    }
                                    catch(err) {
                                    console.error('rest::end', err);
                                    reject(err);
                                    }
                                    });
                                    });

                                    req.on('error', (err) => {
                                    console.error('rest::request', err);
                                    reject(err);
                                    });

                                    req.end();
                                    });
                                    };


                                    As a result you don't have to pass in a callback function, instead getJSON() returns a promise. In the following example the function is used inside of an ExpressJS route handler



                                    router.get('/:id', (req, res, next) => {
                                    rest.getJSON({
                                    host: host,
                                    path: `/posts/${req.params.id}`,
                                    method: 'GET'
                                    }).then(({status, data}) => {
                                    res.json(data);
                                    }, (error) => {
                                    next(error);
                                    });
                                    });


                                    On error it delegates the error to the server error handling middleware.






                                    share|improve this answer


























                                    • Yes,this example is showing how to do it inside an Express get route definition, which many posts here are lacking.

                                      – Micros
                                      Dec 21 '18 at 10:08
















                                    4














                                    This version is based on the initially proposed by bryanmac function which uses promises, better error handling, and is rewritten in ES6.



                                    let http = require("http"),
                                    https = require("https");

                                    /**
                                    * getJSON: REST get request returning JSON object(s)
                                    * @param options: http options object
                                    */
                                    exports.getJSON = function(options)
                                    {
                                    console.log('rest::getJSON');
                                    let reqHandler = +options.port === 443 ? https : http;

                                    return new Promise((resolve, reject) => {
                                    let req = reqHandler.request(options, (res) =>
                                    {
                                    let output = '';
                                    console.log('rest::', options.host + ':' + res.statusCode);
                                    res.setEncoding('utf8');

                                    res.on('data', function (chunk) {
                                    output += chunk;
                                    });

                                    res.on('end', () => {
                                    try {
                                    let obj = JSON.parse(output);
                                    // console.log('rest::', obj);
                                    resolve({
                                    statusCode: res.statusCode,
                                    data: obj
                                    });
                                    }
                                    catch(err) {
                                    console.error('rest::end', err);
                                    reject(err);
                                    }
                                    });
                                    });

                                    req.on('error', (err) => {
                                    console.error('rest::request', err);
                                    reject(err);
                                    });

                                    req.end();
                                    });
                                    };


                                    As a result you don't have to pass in a callback function, instead getJSON() returns a promise. In the following example the function is used inside of an ExpressJS route handler



                                    router.get('/:id', (req, res, next) => {
                                    rest.getJSON({
                                    host: host,
                                    path: `/posts/${req.params.id}`,
                                    method: 'GET'
                                    }).then(({status, data}) => {
                                    res.json(data);
                                    }, (error) => {
                                    next(error);
                                    });
                                    });


                                    On error it delegates the error to the server error handling middleware.






                                    share|improve this answer


























                                    • Yes,this example is showing how to do it inside an Express get route definition, which many posts here are lacking.

                                      – Micros
                                      Dec 21 '18 at 10:08














                                    4












                                    4








                                    4







                                    This version is based on the initially proposed by bryanmac function which uses promises, better error handling, and is rewritten in ES6.



                                    let http = require("http"),
                                    https = require("https");

                                    /**
                                    * getJSON: REST get request returning JSON object(s)
                                    * @param options: http options object
                                    */
                                    exports.getJSON = function(options)
                                    {
                                    console.log('rest::getJSON');
                                    let reqHandler = +options.port === 443 ? https : http;

                                    return new Promise((resolve, reject) => {
                                    let req = reqHandler.request(options, (res) =>
                                    {
                                    let output = '';
                                    console.log('rest::', options.host + ':' + res.statusCode);
                                    res.setEncoding('utf8');

                                    res.on('data', function (chunk) {
                                    output += chunk;
                                    });

                                    res.on('end', () => {
                                    try {
                                    let obj = JSON.parse(output);
                                    // console.log('rest::', obj);
                                    resolve({
                                    statusCode: res.statusCode,
                                    data: obj
                                    });
                                    }
                                    catch(err) {
                                    console.error('rest::end', err);
                                    reject(err);
                                    }
                                    });
                                    });

                                    req.on('error', (err) => {
                                    console.error('rest::request', err);
                                    reject(err);
                                    });

                                    req.end();
                                    });
                                    };


                                    As a result you don't have to pass in a callback function, instead getJSON() returns a promise. In the following example the function is used inside of an ExpressJS route handler



                                    router.get('/:id', (req, res, next) => {
                                    rest.getJSON({
                                    host: host,
                                    path: `/posts/${req.params.id}`,
                                    method: 'GET'
                                    }).then(({status, data}) => {
                                    res.json(data);
                                    }, (error) => {
                                    next(error);
                                    });
                                    });


                                    On error it delegates the error to the server error handling middleware.






                                    share|improve this answer















                                    This version is based on the initially proposed by bryanmac function which uses promises, better error handling, and is rewritten in ES6.



                                    let http = require("http"),
                                    https = require("https");

                                    /**
                                    * getJSON: REST get request returning JSON object(s)
                                    * @param options: http options object
                                    */
                                    exports.getJSON = function(options)
                                    {
                                    console.log('rest::getJSON');
                                    let reqHandler = +options.port === 443 ? https : http;

                                    return new Promise((resolve, reject) => {
                                    let req = reqHandler.request(options, (res) =>
                                    {
                                    let output = '';
                                    console.log('rest::', options.host + ':' + res.statusCode);
                                    res.setEncoding('utf8');

                                    res.on('data', function (chunk) {
                                    output += chunk;
                                    });

                                    res.on('end', () => {
                                    try {
                                    let obj = JSON.parse(output);
                                    // console.log('rest::', obj);
                                    resolve({
                                    statusCode: res.statusCode,
                                    data: obj
                                    });
                                    }
                                    catch(err) {
                                    console.error('rest::end', err);
                                    reject(err);
                                    }
                                    });
                                    });

                                    req.on('error', (err) => {
                                    console.error('rest::request', err);
                                    reject(err);
                                    });

                                    req.end();
                                    });
                                    };


                                    As a result you don't have to pass in a callback function, instead getJSON() returns a promise. In the following example the function is used inside of an ExpressJS route handler



                                    router.get('/:id', (req, res, next) => {
                                    rest.getJSON({
                                    host: host,
                                    path: `/posts/${req.params.id}`,
                                    method: 'GET'
                                    }).then(({status, data}) => {
                                    res.json(data);
                                    }, (error) => {
                                    next(error);
                                    });
                                    });


                                    On error it delegates the error to the server error handling middleware.







                                    share|improve this answer














                                    share|improve this answer



                                    share|improve this answer








                                    edited May 23 '17 at 11:55









                                    Community

                                    11




                                    11










                                    answered Mar 3 '17 at 21:01









                                    maqdunimaqduni

                                    14113




                                    14113













                                    • Yes,this example is showing how to do it inside an Express get route definition, which many posts here are lacking.

                                      – Micros
                                      Dec 21 '18 at 10:08



















                                    • Yes,this example is showing how to do it inside an Express get route definition, which many posts here are lacking.

                                      – Micros
                                      Dec 21 '18 at 10:08

















                                    Yes,this example is showing how to do it inside an Express get route definition, which many posts here are lacking.

                                    – Micros
                                    Dec 21 '18 at 10:08





                                    Yes,this example is showing how to do it inside an Express get route definition, which many posts here are lacking.

                                    – Micros
                                    Dec 21 '18 at 10:08











                                    1














                                    If you just need to make simple get requests and don't need support for any other HTTP methods take a look at: simple-get:



                                    var get = require('simple-get');

                                    get('http://example.com', function (err, res) {
                                    if (err) throw err;
                                    console.log(res.statusCode); // 200
                                    res.pipe(process.stdout); // `res` is a stream
                                    });





                                    share|improve this answer




























                                      1














                                      If you just need to make simple get requests and don't need support for any other HTTP methods take a look at: simple-get:



                                      var get = require('simple-get');

                                      get('http://example.com', function (err, res) {
                                      if (err) throw err;
                                      console.log(res.statusCode); // 200
                                      res.pipe(process.stdout); // `res` is a stream
                                      });





                                      share|improve this answer


























                                        1












                                        1








                                        1







                                        If you just need to make simple get requests and don't need support for any other HTTP methods take a look at: simple-get:



                                        var get = require('simple-get');

                                        get('http://example.com', function (err, res) {
                                        if (err) throw err;
                                        console.log(res.statusCode); // 200
                                        res.pipe(process.stdout); // `res` is a stream
                                        });





                                        share|improve this answer













                                        If you just need to make simple get requests and don't need support for any other HTTP methods take a look at: simple-get:



                                        var get = require('simple-get');

                                        get('http://example.com', function (err, res) {
                                        if (err) throw err;
                                        console.log(res.statusCode); // 200
                                        res.pipe(process.stdout); // `res` is a stream
                                        });






                                        share|improve this answer












                                        share|improve this answer



                                        share|improve this answer










                                        answered Jul 12 '16 at 14:37









                                        benjimanbenjiman

                                        2,01531835




                                        2,01531835























                                            0














                                            Look at request module. Reference here http://www.sitepoint.com/making-http-requests-in-node-js/






                                            share|improve this answer




























                                              0














                                              Look at request module. Reference here http://www.sitepoint.com/making-http-requests-in-node-js/






                                              share|improve this answer


























                                                0












                                                0








                                                0







                                                Look at request module. Reference here http://www.sitepoint.com/making-http-requests-in-node-js/






                                                share|improve this answer













                                                Look at request module. Reference here http://www.sitepoint.com/making-http-requests-in-node-js/







                                                share|improve this answer












                                                share|improve this answer



                                                share|improve this answer










                                                answered Aug 24 '13 at 5:36









                                                saurshazsaurshaz

                                                433516




                                                433516























                                                    0














                                                    Use reqclient: not designed for scripting purpose
                                                    like request or many other libraries. Reqclient allows in the constructor
                                                    specify many configurations useful when you need to reuse the same
                                                    configuration again and again: base URL, headers, auth options,
                                                    logging options, caching, etc. Also has useful features like
                                                    query and URL parsing, automatic query encoding and JSON parsing, etc.



                                                    The best way to use the library is create a module to export the object
                                                    pointing to the API and the necessary configurations to connect with:



                                                    Module client.js:



                                                    let RequestClient = require("reqclient").RequestClient

                                                    let client = new RequestClient({
                                                    baseUrl: "https://myapp.com/api/v1",
                                                    cache: true,
                                                    auth: {user: "admin", pass: "secret"}
                                                    })

                                                    module.exports = client


                                                    And in the controllers where you need to consume the API use like this:



                                                    let client = require('client')
                                                    //let router = ...

                                                    router.get('/dashboard', (req, res) => {
                                                    // Simple GET with Promise handling to https://myapp.com/api/v1/reports/clients
                                                    client.get("reports/clients")
                                                    .then(response => {
                                                    console.log("Report for client", response.userId) // REST responses are parsed as JSON objects
                                                    res.render('clients/dashboard', {title: 'Customer Report', report: response})
                                                    })
                                                    .catch(err => {
                                                    console.error("Ups!", err)
                                                    res.status(400).render('error', {error: err})
                                                    })
                                                    })

                                                    router.get('/orders', (req, res, next) => {
                                                    // GET with query (https://myapp.com/api/v1/orders?state=open&limit=10)
                                                    client.get({"uri": "orders", "query": {"state": "open", "limit": 10}})
                                                    .then(orders => {
                                                    res.render('clients/orders', {title: 'Customer Orders', orders: orders})
                                                    })
                                                    .catch(err => someErrorHandler(req, res, next))
                                                    })

                                                    router.delete('/orders', (req, res, next) => {
                                                    // DELETE with params (https://myapp.com/api/v1/orders/1234/A987)
                                                    client.delete({
                                                    "uri": "orders/{client}/{id}",
                                                    "params": {"client": "A987", "id": 1234}
                                                    })
                                                    .then(resp => res.status(204))
                                                    .catch(err => someErrorHandler(req, res, next))
                                                    })


                                                    reqclient supports many features, but it has some that are not supported by other
                                                    libraries: OAuth2 integration and logger integration
                                                    with cURL syntax, and always returns native Promise objects.






                                                    share|improve this answer




























                                                      0














                                                      Use reqclient: not designed for scripting purpose
                                                      like request or many other libraries. Reqclient allows in the constructor
                                                      specify many configurations useful when you need to reuse the same
                                                      configuration again and again: base URL, headers, auth options,
                                                      logging options, caching, etc. Also has useful features like
                                                      query and URL parsing, automatic query encoding and JSON parsing, etc.



                                                      The best way to use the library is create a module to export the object
                                                      pointing to the API and the necessary configurations to connect with:



                                                      Module client.js:



                                                      let RequestClient = require("reqclient").RequestClient

                                                      let client = new RequestClient({
                                                      baseUrl: "https://myapp.com/api/v1",
                                                      cache: true,
                                                      auth: {user: "admin", pass: "secret"}
                                                      })

                                                      module.exports = client


                                                      And in the controllers where you need to consume the API use like this:



                                                      let client = require('client')
                                                      //let router = ...

                                                      router.get('/dashboard', (req, res) => {
                                                      // Simple GET with Promise handling to https://myapp.com/api/v1/reports/clients
                                                      client.get("reports/clients")
                                                      .then(response => {
                                                      console.log("Report for client", response.userId) // REST responses are parsed as JSON objects
                                                      res.render('clients/dashboard', {title: 'Customer Report', report: response})
                                                      })
                                                      .catch(err => {
                                                      console.error("Ups!", err)
                                                      res.status(400).render('error', {error: err})
                                                      })
                                                      })

                                                      router.get('/orders', (req, res, next) => {
                                                      // GET with query (https://myapp.com/api/v1/orders?state=open&limit=10)
                                                      client.get({"uri": "orders", "query": {"state": "open", "limit": 10}})
                                                      .then(orders => {
                                                      res.render('clients/orders', {title: 'Customer Orders', orders: orders})
                                                      })
                                                      .catch(err => someErrorHandler(req, res, next))
                                                      })

                                                      router.delete('/orders', (req, res, next) => {
                                                      // DELETE with params (https://myapp.com/api/v1/orders/1234/A987)
                                                      client.delete({
                                                      "uri": "orders/{client}/{id}",
                                                      "params": {"client": "A987", "id": 1234}
                                                      })
                                                      .then(resp => res.status(204))
                                                      .catch(err => someErrorHandler(req, res, next))
                                                      })


                                                      reqclient supports many features, but it has some that are not supported by other
                                                      libraries: OAuth2 integration and logger integration
                                                      with cURL syntax, and always returns native Promise objects.






                                                      share|improve this answer


























                                                        0












                                                        0








                                                        0







                                                        Use reqclient: not designed for scripting purpose
                                                        like request or many other libraries. Reqclient allows in the constructor
                                                        specify many configurations useful when you need to reuse the same
                                                        configuration again and again: base URL, headers, auth options,
                                                        logging options, caching, etc. Also has useful features like
                                                        query and URL parsing, automatic query encoding and JSON parsing, etc.



                                                        The best way to use the library is create a module to export the object
                                                        pointing to the API and the necessary configurations to connect with:



                                                        Module client.js:



                                                        let RequestClient = require("reqclient").RequestClient

                                                        let client = new RequestClient({
                                                        baseUrl: "https://myapp.com/api/v1",
                                                        cache: true,
                                                        auth: {user: "admin", pass: "secret"}
                                                        })

                                                        module.exports = client


                                                        And in the controllers where you need to consume the API use like this:



                                                        let client = require('client')
                                                        //let router = ...

                                                        router.get('/dashboard', (req, res) => {
                                                        // Simple GET with Promise handling to https://myapp.com/api/v1/reports/clients
                                                        client.get("reports/clients")
                                                        .then(response => {
                                                        console.log("Report for client", response.userId) // REST responses are parsed as JSON objects
                                                        res.render('clients/dashboard', {title: 'Customer Report', report: response})
                                                        })
                                                        .catch(err => {
                                                        console.error("Ups!", err)
                                                        res.status(400).render('error', {error: err})
                                                        })
                                                        })

                                                        router.get('/orders', (req, res, next) => {
                                                        // GET with query (https://myapp.com/api/v1/orders?state=open&limit=10)
                                                        client.get({"uri": "orders", "query": {"state": "open", "limit": 10}})
                                                        .then(orders => {
                                                        res.render('clients/orders', {title: 'Customer Orders', orders: orders})
                                                        })
                                                        .catch(err => someErrorHandler(req, res, next))
                                                        })

                                                        router.delete('/orders', (req, res, next) => {
                                                        // DELETE with params (https://myapp.com/api/v1/orders/1234/A987)
                                                        client.delete({
                                                        "uri": "orders/{client}/{id}",
                                                        "params": {"client": "A987", "id": 1234}
                                                        })
                                                        .then(resp => res.status(204))
                                                        .catch(err => someErrorHandler(req, res, next))
                                                        })


                                                        reqclient supports many features, but it has some that are not supported by other
                                                        libraries: OAuth2 integration and logger integration
                                                        with cURL syntax, and always returns native Promise objects.






                                                        share|improve this answer













                                                        Use reqclient: not designed for scripting purpose
                                                        like request or many other libraries. Reqclient allows in the constructor
                                                        specify many configurations useful when you need to reuse the same
                                                        configuration again and again: base URL, headers, auth options,
                                                        logging options, caching, etc. Also has useful features like
                                                        query and URL parsing, automatic query encoding and JSON parsing, etc.



                                                        The best way to use the library is create a module to export the object
                                                        pointing to the API and the necessary configurations to connect with:



                                                        Module client.js:



                                                        let RequestClient = require("reqclient").RequestClient

                                                        let client = new RequestClient({
                                                        baseUrl: "https://myapp.com/api/v1",
                                                        cache: true,
                                                        auth: {user: "admin", pass: "secret"}
                                                        })

                                                        module.exports = client


                                                        And in the controllers where you need to consume the API use like this:



                                                        let client = require('client')
                                                        //let router = ...

                                                        router.get('/dashboard', (req, res) => {
                                                        // Simple GET with Promise handling to https://myapp.com/api/v1/reports/clients
                                                        client.get("reports/clients")
                                                        .then(response => {
                                                        console.log("Report for client", response.userId) // REST responses are parsed as JSON objects
                                                        res.render('clients/dashboard', {title: 'Customer Report', report: response})
                                                        })
                                                        .catch(err => {
                                                        console.error("Ups!", err)
                                                        res.status(400).render('error', {error: err})
                                                        })
                                                        })

                                                        router.get('/orders', (req, res, next) => {
                                                        // GET with query (https://myapp.com/api/v1/orders?state=open&limit=10)
                                                        client.get({"uri": "orders", "query": {"state": "open", "limit": 10}})
                                                        .then(orders => {
                                                        res.render('clients/orders', {title: 'Customer Orders', orders: orders})
                                                        })
                                                        .catch(err => someErrorHandler(req, res, next))
                                                        })

                                                        router.delete('/orders', (req, res, next) => {
                                                        // DELETE with params (https://myapp.com/api/v1/orders/1234/A987)
                                                        client.delete({
                                                        "uri": "orders/{client}/{id}",
                                                        "params": {"client": "A987", "id": 1234}
                                                        })
                                                        .then(resp => res.status(204))
                                                        .catch(err => someErrorHandler(req, res, next))
                                                        })


                                                        reqclient supports many features, but it has some that are not supported by other
                                                        libraries: OAuth2 integration and logger integration
                                                        with cURL syntax, and always returns native Promise objects.







                                                        share|improve this answer












                                                        share|improve this answer



                                                        share|improve this answer










                                                        answered Apr 5 '17 at 23:03









                                                        Mariano RuizMariano Ruiz

                                                        1,9912223




                                                        1,9912223























                                                            -1














                                                            ## you can use request module and promise in express to make any request ##
                                                            const promise = require('promise');
                                                            const requestModule = require('request');

                                                            const curlRequest =(requestOption) =>{
                                                            return new Promise((resolve, reject)=> {
                                                            requestModule(requestOption, (error, response, body) => {
                                                            try {
                                                            if (error) {
                                                            throw error;
                                                            }
                                                            if (body) {

                                                            try {
                                                            body = (body) ? JSON.parse(body) : body;
                                                            resolve(body);
                                                            }catch(error){
                                                            resolve(body);
                                                            }

                                                            } else {

                                                            throw new Error('something wrong');
                                                            }
                                                            } catch (error) {

                                                            reject(error);
                                                            }
                                                            })
                                                            })
                                                            };

                                                            const option = {
                                                            url : uri,
                                                            method : "GET",
                                                            headers : {

                                                            }
                                                            };


                                                            curlRequest(option).then((data)=>{
                                                            }).catch((err)=>{
                                                            })





                                                            share|improve this answer


























                                                            • (As it happens, it won't solve the problem. This code will listen for a request but the question is asking how to send a request)

                                                              – Quentin
                                                              Jan 30 '18 at 11:53






                                                            • 1





                                                              it is fixed, you can try it out. @Quentin

                                                              – izhar ahmad
                                                              Jan 30 '18 at 12:09


















                                                            -1














                                                            ## you can use request module and promise in express to make any request ##
                                                            const promise = require('promise');
                                                            const requestModule = require('request');

                                                            const curlRequest =(requestOption) =>{
                                                            return new Promise((resolve, reject)=> {
                                                            requestModule(requestOption, (error, response, body) => {
                                                            try {
                                                            if (error) {
                                                            throw error;
                                                            }
                                                            if (body) {

                                                            try {
                                                            body = (body) ? JSON.parse(body) : body;
                                                            resolve(body);
                                                            }catch(error){
                                                            resolve(body);
                                                            }

                                                            } else {

                                                            throw new Error('something wrong');
                                                            }
                                                            } catch (error) {

                                                            reject(error);
                                                            }
                                                            })
                                                            })
                                                            };

                                                            const option = {
                                                            url : uri,
                                                            method : "GET",
                                                            headers : {

                                                            }
                                                            };


                                                            curlRequest(option).then((data)=>{
                                                            }).catch((err)=>{
                                                            })





                                                            share|improve this answer


























                                                            • (As it happens, it won't solve the problem. This code will listen for a request but the question is asking how to send a request)

                                                              – Quentin
                                                              Jan 30 '18 at 11:53






                                                            • 1





                                                              it is fixed, you can try it out. @Quentin

                                                              – izhar ahmad
                                                              Jan 30 '18 at 12:09
















                                                            -1












                                                            -1








                                                            -1







                                                            ## you can use request module and promise in express to make any request ##
                                                            const promise = require('promise');
                                                            const requestModule = require('request');

                                                            const curlRequest =(requestOption) =>{
                                                            return new Promise((resolve, reject)=> {
                                                            requestModule(requestOption, (error, response, body) => {
                                                            try {
                                                            if (error) {
                                                            throw error;
                                                            }
                                                            if (body) {

                                                            try {
                                                            body = (body) ? JSON.parse(body) : body;
                                                            resolve(body);
                                                            }catch(error){
                                                            resolve(body);
                                                            }

                                                            } else {

                                                            throw new Error('something wrong');
                                                            }
                                                            } catch (error) {

                                                            reject(error);
                                                            }
                                                            })
                                                            })
                                                            };

                                                            const option = {
                                                            url : uri,
                                                            method : "GET",
                                                            headers : {

                                                            }
                                                            };


                                                            curlRequest(option).then((data)=>{
                                                            }).catch((err)=>{
                                                            })





                                                            share|improve this answer















                                                            ## you can use request module and promise in express to make any request ##
                                                            const promise = require('promise');
                                                            const requestModule = require('request');

                                                            const curlRequest =(requestOption) =>{
                                                            return new Promise((resolve, reject)=> {
                                                            requestModule(requestOption, (error, response, body) => {
                                                            try {
                                                            if (error) {
                                                            throw error;
                                                            }
                                                            if (body) {

                                                            try {
                                                            body = (body) ? JSON.parse(body) : body;
                                                            resolve(body);
                                                            }catch(error){
                                                            resolve(body);
                                                            }

                                                            } else {

                                                            throw new Error('something wrong');
                                                            }
                                                            } catch (error) {

                                                            reject(error);
                                                            }
                                                            })
                                                            })
                                                            };

                                                            const option = {
                                                            url : uri,
                                                            method : "GET",
                                                            headers : {

                                                            }
                                                            };


                                                            curlRequest(option).then((data)=>{
                                                            }).catch((err)=>{
                                                            })






                                                            share|improve this answer














                                                            share|improve this answer



                                                            share|improve this answer








                                                            edited Jan 30 '18 at 12:07

























                                                            answered Jan 30 '18 at 11:46









                                                            izhar ahmadizhar ahmad

                                                            212




                                                            212













                                                            • (As it happens, it won't solve the problem. This code will listen for a request but the question is asking how to send a request)

                                                              – Quentin
                                                              Jan 30 '18 at 11:53






                                                            • 1





                                                              it is fixed, you can try it out. @Quentin

                                                              – izhar ahmad
                                                              Jan 30 '18 at 12:09





















                                                            • (As it happens, it won't solve the problem. This code will listen for a request but the question is asking how to send a request)

                                                              – Quentin
                                                              Jan 30 '18 at 11:53






                                                            • 1





                                                              it is fixed, you can try it out. @Quentin

                                                              – izhar ahmad
                                                              Jan 30 '18 at 12:09



















                                                            (As it happens, it won't solve the problem. This code will listen for a request but the question is asking how to send a request)

                                                            – Quentin
                                                            Jan 30 '18 at 11:53





                                                            (As it happens, it won't solve the problem. This code will listen for a request but the question is asking how to send a request)

                                                            – Quentin
                                                            Jan 30 '18 at 11:53




                                                            1




                                                            1





                                                            it is fixed, you can try it out. @Quentin

                                                            – izhar ahmad
                                                            Jan 30 '18 at 12:09







                                                            it is fixed, you can try it out. @Quentin

                                                            – izhar ahmad
                                                            Jan 30 '18 at 12:09




















                                                            draft saved

                                                            draft discarded




















































                                                            Thanks for contributing an answer to Stack Overflow!


                                                            • Please be sure to answer the question. Provide details and share your research!

                                                            But avoid



                                                            • Asking for help, clarification, or responding to other answers.

                                                            • Making statements based on opinion; back them up with references or personal experience.


                                                            To learn more, see our tips on writing great answers.




                                                            draft saved


                                                            draft discarded














                                                            StackExchange.ready(
                                                            function () {
                                                            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f9577611%2fhttp-get-request-in-node-js-express%23new-answer', 'question_page');
                                                            }
                                                            );

                                                            Post as a guest















                                                            Required, but never shown





















































                                                            Required, but never shown














                                                            Required, but never shown












                                                            Required, but never shown







                                                            Required, but never shown

































                                                            Required, but never shown














                                                            Required, but never shown












                                                            Required, but never shown







                                                            Required, but never shown







                                                            Popular posts from this blog

                                                            Costa Masnaga

                                                            Fotorealismo

                                                            Sidney Franklin