我试图向Node发送一个React状态,其思想是当用户输入邮政编码时,
我做了1,2,4,但3给了我一个错误。 下面是需要接收React状态的节点代码:
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)
为什么会发生这种情况?我该如何解决它? 提前谢谢你!
更新I将节点代码更改为:
......
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)
尝试启用COR并设置Application/JSON头。 您需要启用cors才能到达第三个IP。 此外,您需要适合他们的标题。 尝试更深入地了解天气api的需求,并首先尝试使用邮递员,如果这样做可行,您可以使用输出“代码”选择来获取标题。 你不必向邮递员做帐目,即使它试图让你。