Axios GET 请求返回空对象
2020-10-20
1795
“dataService”类中的“getData”函数向 API 执行 GET 请求,“updateData”函数中的 console.log 确实打印了正确的信息,但“http://localhost:xxxx/api/data”返回了一个空对象。我认为这是由于异步问题造成的,但我不知道如何修复它。有什么想法吗?
dataService.ts:
import { Format } from '../types';
import axios from 'axios';
const token = process.env.TOKEN;
const url = `https://www.something.com/somequery?someapikey=${token}`;
const getData = async () => {
try {
const response = await axios.get<Format>(url);
return response.data;
} catch (error) {
console.error(error);
}
};
const updateData = async (): Promise<Format | undefined> => {
const allData = await getData();
console.log(allData, 'allData in backend');
//edit allData to suitable format here
return allData;
};
export default {
updateData
};
data.ts:
import express from 'express';
import dataService from '../services/dataService';
const router = express.Router();
router.get('/', (_req, res) => {
res.send(dataService.updateData());
});
export default router;
index.ts:
import express from 'express';
const app = express();
...
import dataRouter from './routes/data';
...
app.use(express.json());
...
app.use('/api/data', dataRouter);
...
2个回答
修复
getData
以返回 Promise,成功时解析一个,失败时拒绝一个。
当您有异步函数时,预计会返回承诺,尤其是当您想要
await
它时。
const getData = async () => {
try {
const response = await axios.get<Format>(url);
return Promise.resolve(response.data);
} catch (error) {
console.error(error);
return Promise.reject()
}
};`
此外,updatr 数据应恢复承诺
const updateData = async (): Promise<Format | undefined> => {
const allData = await getData();
console.log(allData, 'allData in backend');
//edit allData to suitable format here
return Promise.resolve(allData);
};
您还需要等待 updateData :
import express from 'express';
import dataService from '../services/dataService';
const router = express.Router();
router.get('/', (_req, res) => {
dataService.updateData()
.then(data=>{
res.send(data)
})
.catch(error=>{})
});
export default router;
Tawfik Nasser
2020-10-20
Response.send
应该接收来自
updateData()
的解析值,而不是其返回值,因为异步函数的返回值是一个 promise 对象,添加缺失的 await 将解决问题:
res.send(await dataService.updateData());
Hoang Dao
2020-10-21