REST Api:无法在前端获取数据(NodeJS/React)
2022-07-21
151
我尝试将服务器端的 JSON 文件中的数据发送到前端。在 Postman 上调用时,数据在后端可用,但是当我在前端调用 listPhones() 时,它返回未定义。我希望这足够清楚:
Back end route:
const express = require('express');
const router = express.Router();
const data = require('./../data/phones.json');
router.get('/', (req, res, next) => {
res.json({ data });
});
---------------------------------------------------------
Front end proxy (the base URL is mounted on "api"):
import api from './api';
export const listPhones = () => {
api.get('/phones').then(response => response.data);
};
--------------------------------------------------------
Page to be rendered using listPhones a service:
const [phones, setPhones] = useState([]);
useEffect(() => {
listPhones().then(data => {
setPhones(data.phones);
});
}, []);
1个回答
如果您想在
useEffect
中处理响应,您的
listPhones
函数应该返回
Promise
:
export const listPhones = () => {
return api.get('/phones');
};
然后您应该能够使用以下命令访问数据:
useEffect(() => {
listPhones().then(response => {
setPhones(response.data);
}).catch(err => console.log(err));
}, []);
lpizzinidev
2022-07-21