404 error while sending data from React to Node?

Viewed 349

I'm trying to send a React state to Node, the idea is that when a user inputs a postcode,

  1. React finds the geological coordinates,
  2. store it in a state
  3. React sends this state to an open weather api in Node code,
  4. Node then fetches the weather data and sends back to React.

I have done 1, 2, 4, but 3 gave me an error. Here is the Node code which needs to receive the React state:

const axios = require('axios');
const dotenv = require('dotenv');
dotenv.config();

module.exports = (app) => {

    app.get('/search-location', (req, res) => {
        res.send('This is the search location page')
    });

    app.post('/search-location', (req, res) => {

        let baseUrl = `http://api.openweathermap.org/data/2.5/weather?`,
            apiKey = `&appid=${process.env.REACT_APP_WEATHER_API_KEY}`,
            coordinates = `lat=` + coord[0] + `&lon=` + coord[1], // here I need the coordinates from React state
            apiUrl = baseUrl + coordinates + apiKey;
        axios.get(apiUrl)
            .then(response => {
                res.json(response.data);
                console.log(response);
            })
            .catch(error => {
                res.redirect('/error');
                console.log(error);
                console.log('search location error')
            });
    });
}

Here is the React method to send the state to Node (I'm using a dummy coord variable to test):

sendToNode() {
    
    let coord = {
        longitude: 50,
        latitude: -2.1
    }

    axios.post('http://localhost:4000/search-location', coord)
        .then((response) => {
            console.log(response);
        }, (error) => {
            console.log(error); // here is line 36 where the 404 error logged in console
        });
}

I have googled as much as I could, the above method seemed to be correct, but I'm getting the following error in Chrome console:

xhr.js:178 GET http://localhost:4000/error 404 (Not Found)
WeatherTile.js:36 Error: Request failed with status code 404
    at createError (createError.js:16)
    at settle (settle.js:17)
    at XMLHttpRequest.handleLoad (xhr.js:61)

Why does this happen and how could I fix it? Thank you in advance!

UPDATE I changed the Node code to:

......
app.post('/search-location', (req, res) => {
        let coord = req.body.coord;
        let baseUrl = `http://api.openweathermap.org/data/2.5/weather?`,
            apiKey = `&appid=${process.env.REACT_APP_WEATHER_API_KEY}`,
            coordinates = `lat=` + coord[0] + `&lon=` + coord[1],
            /* coordinates = `lat=` + `51.5842` + `&lon=` + `-2.9977`, */
            apiUrl = baseUrl + coordinates + apiKey;
......

Now I get this error in Chrome console:

POST http://localhost:4000/search-location 500 (Internal Server Error)
WeatherTile.js:36 Error: Request failed with status code 500
    at createError (createError.js:16)
    at settle (settle.js:17)
    at XMLHttpRequest.handleLoad (xhr.js:61)
2 Answers

try enabling cors and setting application/json headers. You need to have cors enabled to reach a 3rd ip. Also you need to fit their headers. Try looking deeper into the requirements of the weather api and try with POSTMAN first, and if that works you can get the headers using the output "code" selection. You dont have to make an account with postman, even though it tries to make you.

Thanks to all the help, I think pavan kumar's comment pointed me to the correct direction. After adding this line let coord = req.body.coord; to the post method, I was able to see the request body by console.log(coord):

{ latitude: 50, longitude: -2.1 }

The 500 internal server error was caused by calling coord[0] and coord[1], as coord was an object rather than an array. The error disappeared after changing to

coordinates = `lat=` + coord.latitude + `&lon=` + coord.longitude;

Thanks again.

Related