Ignat Ospadov Ignat Ospadov - 19 days ago 7
Node.js Question

Express - Passing Client Data to an API and returning Data to Client from the API

I am new to express and having trouble writing a script that performs the following:


  1. Client makes a POST request to server, passing geolocation data in the request.

  2. Server makes a HTTPS GET request to an API using the geolocation data from the client in the url.

  3. Server passes the response (JSON object) from the API to the client.



So far I have been able to access the geolocation data from the client but I am not sure how to use express to do #2 and #3.

This is my code for #1:

app.post('/locationdata', function (req, res, next) {
apiURL =
'https://api.darksky.net/forecast/166731d8eab28d33a26c5a51023eff4c/'+req.body.toString();
})

Answer

You can use request node module to make a GET request.

app.post('/locationdata', function (req, res, next) {
    var apiURL =  'https://api.darksky.net/forecast/166731d8eab28d33a26c5a51023eff4c/' + req.body.toString();

    var request = require('request');
    request(apiURL, function (error, response, body) {
    if (!error && response.statusCode == 200) {
       res.send(body); // res is your original response 
    }
  })
})