Moshe
Moshe

Reputation: 2674

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 */})
}

Upvotes: 7

Views: 25019

Answers (2)

Eskay Amadeus
Eskay Amadeus

Reputation: 318

The accepted answer is good, but in case anyone comes across this question later, let's keep in mind that as of February, 2020, request is now deprecated.

So what can we do? We can use another library. I would suggest Axios.

Install it and do something like:

const axios = require('axios')


const url = "https://example.com"

const getData = async (url) => {
  try {
    const response = await axios.get(url)
    const data = response.data
    console.log(data)
  } catch (error) {
    console.log(error)
  }
}

getData(url)

Upvotes: 14

John Dews
John Dews

Reputation: 513

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.

Upvotes: 21

Related Questions