Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making external get request with Express

so I have the following Scenario; I have a private API key that Angular will show in XHR request. To combat this, I decided to use Express as a proxy and make server side requests. However, I cannot seem to find documentation on how to make my own get requests.

Architecture:

Angular makes request to /api/external-api --> Express handles the route and makes request to externalURL with params in req.body.params and attaches API key from config.apiKey. The following is pseudocode to imitate what I'm trying to accomplish:

router.get('/external-api', (req, res) => {
  externalRestGetRequest(externalURL, req.body.params, config.apiKey)
  res.send({ /* get response here */})
}
like image 988
Moshe Avatar asked Nov 27 '22 13:11

Moshe


1 Answers

You are half way there! You need something to make that request for you. Such as the npm library request.

In your route something like

var request = require('request');


router.get('/external-api', function(req, res){ 

    request('http://www.google.com', function (error, response, body) {
          console.log('error:', error); // Print the error if one occurred and handle it
          console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
          res.send(body)
    });

})

This allows you to make any type of request using whatever URL or API keys you need. However it's important to note you also need to handle any errors or bad response codes.

like image 83
John Dews Avatar answered Dec 09 '22 21:12

John Dews