【问题标题】:Problem sending json from express to react从快递发送 json 以做出反应的问题
【发布时间】:2020-09-14 12:48:24
【问题描述】:

我正在学习 express,但在将 json 从我的 express 服务器发送到我的 react 应用程序时遇到问题。

在我的快速服务器上,我对 openweathermap API 进行 API 调用,然后发送 JSON 以在我使用 axios 获取它的地方做出反应。问题是,我的 react 应用程序将获取 JSON,但数据字段将为空白,我尝试使用 res.json({name:"blank"}) 手动发送 JSON,但我的 API 调用的结果不会发送。

第一个代码 sn-p 是我的 Express 服务器,第二个代码 sn-p 是我的 React 应用程序。最后一个 sn-p 是我得到的错误。

const express = require('express');

const path = require('path');

const app = express();

const fetch = require('node-fetch');

app.get('/test', (req, res) =>
    res.send('Welcome to backend this is from node')
);

const port = process.env.PORT || 3001;

app.listen(port);

console.log('App is listening on port ', port);

const apiCall = async () => {
    try {
        const KEY = fd3909829b4fbfcfcca7c595a56c7632;
        const api_res = await fetch(
            'api.openweathermap.org/data/2.5/weather?q=toronto&appid=${KEY}'
        );
        response = await api_res.json();
        console.log(response);
        return response;
    } catch (error) {
        console.log('error: ', error);
    }
};

app.get('/weather', async (req, res) => {
    const data = await apiCall();
    res.json(data);
});

import React from 'react';
import './App.css';
import axios from 'axios';

import Weather from './components/weather';

const hitBackend = () => {
    axios.get('/weather').then((res) => {
        console.log(res);
    });
};

function App() {
    return (
        <div className='App'>
            <Weather />
            <button onClick={hitBackend}>Send Request!</button>
        </div>
    );
}

export default App;
error:  ReferenceError: fd3909829b4fbfcfcca7c595a56c7632 is not defined
[server]     at apiCall (C:\Users\Jalal\Desktop\Coding\React\weather\server\index.js:21:15)
[server]     at C:\Users\Jalal\Desktop\Coding\React\weather\server\index.js:34:21
[server]     at Layer.handle [as handle_request] (C:\Users\Jalal\Desktop\Coding\React\weather\node_modules\express\lib\router\layer.js:95:5)
[server]     at next (C:\Users\Jalal\Desktop\Coding\React\weather\node_modules\express\lib\router\route.js:137:13)
[server]     at Route.dispatch (C:\Users\Jalal\Desktop\Coding\React\weather\node_modules\express\lib\router\route.js:112:3)
[server]     at Layer.handle [as handle_request] (C:\Users\Jalal\Desktop\Coding\React\weather\node_modules\express\lib\router\layer.js:95:5)
[server]     at C:\Users\Jalal\Desktop\Coding\React\weather\node_modules\express\lib\router\index.js:281:22
[server]     at Function.process_params (C:\Users\Jalal\Desktop\Coding\React\weather\node_modules\express\lib\router\index.js:335:12)
[server]     at next (C:\Users\Jalal\Desktop\Coding\React\weather\node_modules\express\lib\router\index.js:275:10)
[server]     at expressInit (C:\Users\Jalal\Desktop\Coding\React\weather\node_modules\express\lib\middleware\init.js:40:5)

【问题讨论】:

    标签: javascript node.js json reactjs express


    【解决方案1】:

    您需要等待您的 apiCall,因为它是异步的。

    app.get('/weather', async (req, res, next) => { 
        const data = await apiCall();
        res.send(data);
    });
    

    【讨论】:

    • 你应该使用res.json(...)
    【解决方案2】:

    您的 API 密钥变量设置不正确

    const KEY = fd3909829b4fbfcfcca7c595a56c7632;
    

    应该是

    const KEY = "fd3909829b4fbfcfcca7c595a56c7632";
    

    接下来你没有正确处理错误。 因为您正在捕获 callApi 方法中的错误, 当您将响应发送回响应时,您无法知道 apiCall 函数是否成功。

    此外,为了在字符串中使用 ${} 表示法,您需要使用 `` 而不是 " "。

    所以

    'api.openweathermap.org/data/2.5/weather?q=toronto&appid=${KEY}'
    

    变成

    `https://www.api.openweathermap.org/data/2.5/weather?q=toronto&appid=${KEY}`
    

    这就是我将如何编码以正确捕获错误并在请求失败时让反应知道。

    app.get('/weather', async (req, res) => {
        try {
            const KEY = "fd3909829b4fbfcfcca7c595a56c7632";
            const api_res = await fetch(
                `https://www.api.openweathermap.org/data/2.5/weather?q=toronto&appid=${KEY}`
            );
            response = await api_res.json();
            console.log(response);
            return res.json(response);;
        } catch (error) {
            console.log('error: ', error);
            return res.status(400).send('error: ' + error.toString());
        }
        
    });
    

    【讨论】:

    • 另外,您不应该将 Api 密钥存储在您的代码中,或者将其发布到堆栈溢出大声笑。您应该研究存储和使用环境变量。我推荐一个名为 dotenv npmjs.com/package/dotenv 的包,然后您可以将变量添加到 .env 文件中。 .env 文件也应该在 .gitignore 文件中进行监听,这样您就可以将您的秘密变量(如 api 密钥)隐藏起来,不让坏的互联网人看到。 :)
    • api.openweathermap.org/data/2.5/weather?q=toronto&amp;appid=${KEY} 应该是https://www.api.openweathermap.org/data/2.5/weather?q=toronto&amp;appid=${KEY}
    【解决方案3】:

    您的 express 应用程序的主要问题是您没有在路由上等待 apiCall 方法。因此,该函数正在执行,但并未等待您那里的异步代码。

    所以,你需要像这样等待:

    app.get("/weather", async (req, res, next) => {
      const weather = await apiCall()
      res.send(weather);
    });
    

    另外,我看到您正在使用 fetch 从天气中获取 API 响应,但不需要任何模块。 Fetch 是一个浏览器 API。为此,您可以安装node-fetch 或使用 axios。

    【讨论】:

      猜你喜欢
      • 2021-10-24
      • 2022-10-20
      • 2023-01-13
      • 1970-01-01
      • 1970-01-01
      • 2019-10-07
      • 1970-01-01
      • 1970-01-01
      • 2021-03-18
      相关资源
      最近更新 更多