从React向Node发送数据时出现404错误?

4

我想把React状态传递给Node,目的是当用户输入邮编时,

  1. React获取地理坐标
  2. 将其存储在状态中
  3. React将此状态发送到Node代码中的开放天气API
  4. 然后,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)

1
在您的Node代码中,从浏览器访问请求正文并访问坐标。 - pavan kumar
1
@pavankumar,您能否发布一个答案并详细说明一下? - one-hand-octopus
1
我建议避免在此处重定向到/errorres.redirect('/error');这应该会为您提供有关上面的axios.get出现问题的更多信息。祝你好运。 - Carl von Blixen
1
访问请求主体,例如req.body.<你的变量>。尝试在Node控制台中打印req.body,以便查看请求正文中的内容。尝试在记录之前解析req。 - pavan kumar
所以你遇到了 "内部服务器错误" ... 服务器的控制台显示了什么? - Quentin
输出您的coord变量并检查结果。它是否具有预期的值和预期的类型? - jaimish11
2个回答

0
尝试启用CORS并设置application/json头。您需要启用CORS才能访问第三方IP。此外,您需要适应其标头。尝试深入了解天气API的要求,并首先使用POSTMAN尝试一下,如果可以使用,则可以使用输出“代码”选择获取标头。您不必使用postman创建帐户,即使它试图让您这样做。

0
感谢所有的帮助,我认为Pavan Kumar的评论指引了我正确的方向。在post方法中添加这一行let coord = req.body.coord;后,我能够通过console.log(coord)看到请求主体:
{ latitude: 50, longitude: -2.1 }

500内部服务器错误是由于调用coord [0]coord [1]引起的,因为coord是一个对象而不是一个数组。更改为数组后,错误消失了。

coordinates = `lat=` + coord.latitude + `&lon=` + coord.longitude;

再次感谢。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接