我想把React状态传递给Node,目的是当用户输入邮编时,
- React获取地理坐标
- 将其存储在状态中
- React将此状态发送到Node代码中的开放天气API
- 然后,Node获取天气数据并发送回React。
我已经完成了1、2、4,但3给了我一个错误。这是需要接收React状态的Node代码:
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')
});
});
}
这里是发送状态到 Node 的 React 方法(我使用一个虚拟的
coord
变量进行测试):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
});
}
我已经尽力谷歌了,上述方法似乎是正确的,但我在Chrome控制台中却遇到了以下错误:
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)
为什么会发生这种情况,我该如何解决?谢谢您的帮助!
更新:我将Node代码更改为:
......
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;
......
现在我在Chrome控制台中看到了这个错误:
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)
/error
:res.redirect('/error');
这应该会为您提供有关上面的axios.get
出现问题的更多信息。祝你好运。 - Carl von Blixen