首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将json从express发送到react时出现问题

将json从express发送到react时出现问题
EN

Stack Overflow用户
提问于 2020-09-14 20:48:25
回答 3查看 441关注 0票数 0

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

在我的express服务器上,我调用JSON,然后将openweathermap发送到我使用axios获取它的react。问题是,我的react应用程序将获得JSON,但数据字段将为空,我尝试使用res.json({name:"blank"})手动发送JSON,但我的API调用的结果不会。

第一个代码片段是我的Express服务器,第二个代码片段是我的React应用。最后一个片段是我得到的错误。

代码语言:javascript
运行
复制
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);
});
代码语言:javascript
运行
复制
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;
代码语言:javascript
运行
复制
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)
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2020-09-14 21:42:45

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

代码语言:javascript
运行
复制
const KEY = fd3909829b4fbfcfcca7c595a56c7632;

应该是

代码语言:javascript
运行
复制
const KEY = "fd3909829b4fbfcfcca7c595a56c7632";

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

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

所以

代码语言:javascript
运行
复制
'api.openweathermap.org/data/2.5/weather?q=toronto&appid=${KEY}'

变成了

代码语言:javascript
运行
复制
`https://www.api.openweathermap.org/data/2.5/weather?q=toronto&appid=${KEY}`

这就是我如何对它进行编码,以便正确地捕获错误,并让react知道请求是否失败。

代码语言:javascript
运行
复制
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());
    }
    
});
票数 0
EN

Stack Overflow用户

发布于 2020-09-14 20:54:46

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

代码语言:javascript
运行
复制
app.get('/weather', async (req, res, next) => { 
    const data = await apiCall();
    res.send(data);
});
票数 1
EN

Stack Overflow用户

发布于 2020-09-14 21:00:06

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

因此,您需要等待,如下所示:

代码语言:javascript
运行
复制
app.get("/weather", async (req, res, next) => {
  const weather = await apiCall()
  res.send(weather);
});

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63884664

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档