我正在学习express,在从express服务器向react应用程序发送json时遇到了问题。
在我的express服务器上,我调用JSON,然后将openweathermap
发送到我使用axios
获取它的react。问题是,我的react应用程序将获得JSON,但数据字段将为空,我尝试使用res.json({name:"blank"})
手动发送JSON,但我的API调用的结果不会。
第一个代码片段是我的Express服务器,第二个代码片段是我的React应用。最后一个片段是我得到的错误。
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)
发布于 2020-09-14 21:42:45
您的API密钥变量设置不正确
const KEY = fd3909829b4fbfcfcca7c595a56c7632;
应该是
const KEY = "fd3909829b4fbfcfcca7c595a56c7632";
接下来,您没有正确处理错误。因为您正在捕获callApi方法中的错误,所以当您将响应发送回react时,您无法知道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}`
这就是我如何对它进行编码,以便正确地捕获错误,并让react知道请求是否失败。
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());
}
});
发布于 2020-09-14 20:54:46
你需要等待你的apiCall
,因为它是异步的。
app.get('/weather', async (req, res, next) => {
const data = await apiCall();
res.send(data);
});
发布于 2020-09-14 21:00:06
你的express应用程序的主要问题是你没有在你的路线上等待apiCall方法。因此,该函数正在执行,但不等待您在那里拥有的异步代码。
因此,您需要等待,如下所示:
app.get("/weather", async (req, res, next) => {
const weather = await apiCall()
res.send(weather);
});
此外,我还看到您正在使用fetch从天气获取API响应,但不需要任何模块。Fetch是一种浏览器API。为此,您可以安装node-fetch
或使用axios。
https://stackoverflow.com/questions/63884664
复制相似问题