I'm trying to send a React state to Node, the idea is that when a user inputs a postcode,
- React finds the geological coordinates,
- store it in a state
- React sends this state to an open weather api in Node code,
- 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)