【发布时间】:2020-11-22 16:20:45
【问题描述】:
我正在尝试向 Node 发送 React 状态,其想法是当用户输入邮政编码时,
- 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)
为什么会发生这种情况,我该如何解决?提前谢谢!
更新我将节点代码更改为:
......
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)
【问题讨论】:
-
在您的节点代码中,从浏览器访问请求正文并访问坐标
-
@pavankumar 你能发表一个答案并详细说明吗?
-
我会避免重定向到
/error此处:res.redirect('/error');这应该为您提供有关上述axios.get中出现问题的更多信息。祝你好运。 ?????? -
像 req.body 一样访问请求体。,尝试在节点控制台中打印 req.body,以便查看请求体中的内容,尝试在记录之前解析 req
-
所以你有一个内部服务器错误...... 服务器的控制台说什么?
标签: javascript node.js reactjs