Search code examples
node.jsajaxangulargetrequest

Error when requesting API from Angular and Nodejs


I am attempting to use a Nodejs server as a proxy server to get around CORS of specific API's, such as darksky.net or googleapis. As shown in my Angular 8 code below, I try to send a get request to my NodeJS server, passing three parameters. Once the NodeJs server has received these parameters, I request the API, but I get a 404 error in return.

Angular code:

this.http.get('search/coords/', 
    {
      params: {
        address: this.street,
        city: this.city,
        state: this.state
      }
    }).subscribe(data => {
      this.lattitude = data['results']['geometry']['location']['lat'];
      this.longitude = data['results']['geometry']['location']['lon'];
      console.log(this.lattitude);
      console.log(this.longitude);
      this.coords = {
        lat: this.lattitude,
        lon: this.longitude
      };
    });
    return this.coords;
  }

And here is my current Nodejs/Express code:

const express = require('express')
const path = require('path');
const http = require('http');
const bodyParser = require('body-parser');
var request = require('request');

const app = express();
var url = "";

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({'extended': 'false'}));
app.use(cors());

app.get('search/coords/', function (req, res) {
    var street = req.query.address;
    var city = req.query.city;
    var state = req.query.state;
    url = "https://maps.googleapis.com/maps/api/geocode/json?address=" + street + "," + city + "," + state + "&key=blah/"
    request(url, function(error, response, body) {
        if (!error && response.statusCode == 200) {
            var info = JSON.parse(body);
            res.send(info);
        }
    })
});

Specifically, I receieve a GET 404 not found error and an ERROR HttpErrorResponse {headers: HttpHeaders, status: 404, statusText: "Not Found", url: "http://localhost:4200/search/coords/?address......." I'm new to angular and nodejs, so any help would be much appreciated.


Solution

  • There are two problems:

    1. First is that you did not start the Node server
    2. Second is that if you call this.http.get('search/coords', ...) then the default domain for that request is the current one, which is http://localhost:4200 and that is not you Node server port.

    To make it work, you need to address both of the above.

    So firstly, add this code to the Node.js server file (at the very bottom) to make it listen on some port:

    app.listen(3000, () => {
    
        console.log('Listening on port', 3000);
    });
    

    Then, modify your Angular code to make it look like this:

    this.http.get('http://localhost:3000/search/coords/', ....);
    

    It should work that way.