我正在尝试向 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)
最佳答案
尝试启用 cors 并设置 application/json header 。您需要启用 cors 才能达到第三个 ip。您还需要适合他们的标题。尝试更深入地研究天气 api 的要求并首先尝试使用 POSTMAN,如果可行,您可以使用输出“代码”选择获取标题。你不必在 postman 那里注册一个帐户,即使它试图让你注册。
关于javascript - 从 React 向 Node 发送数据时出现 404 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63215223/