**已关闭。**此问题需要debugging details。它目前不接受回答。
编辑问题以包括desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem。这将帮助其他人回答这个问题。
5天前关闭。
Improve this questiongetDocuments
请求从未完成/保持挂起。我错过了什么?
App.js
import React, { useState, useEffect } from 'react';
import Grid from './Grid';
import apis from '../api/index';
export default function App(props) {
const [documents, setDocuments] = useState([]);
useEffect(() => {
async function initialize() {
await apis.getDocuments().then(documents => {
setDocuments(documents.data.data);
});
}
initialize();
}, []);
return ( <Grid documents={documents} /> )
}
Controller.js
const fetch = require('node-fetch');
exports.getDocuments = async (req, res) => {
// added 'return' before fetch
return fetch('EXTERNAL API ENDPOINT', {
method: 'GET',
headers: {"api-key": "API KEY"}
})
.then(res => res.json())
.then(json => {
console.log(json);
return json
}).catch(err => console.log(err));
};
我也尝试了这个语法:
// added cors
exports.getDocuments = async () => {
console.log("getting documents...");
const response = await fetch(URL, {
method: 'GET',
mode: 'cors',
headers: {
"Content-Type": "application/json",
"x-api-key": "KEY"
}
})
const result = await response.json();
console.log('result', result);
return result;
};
服务器index.js
const express = require('express');
const cors = require('cors');
const { getDocuments } = require('./controllers/Controller');
const router = require('./routes');
const app = express();
// enable CORS for all origins to allow development with local server
app.use(cors({credentials: true, origin: "http://localhost:3002"}));
app.use('/api', router);
app.get('/', (req, res) => {
res.send('This is the backend/API');
})
app.set('port', process.env.PORT || 4200);
const server = app.listen(app.get('port'), () => {
console.log(`Express running on port ${server.address().port}`);
});
服务器在localhost上:
2条答案
按热度按时间mtb9vblg1#
假设像这样将
getDocuments
添加到/api
路由器Express不使用路由处理程序的返回值。相反,您需要发送一个响应。
您需要将控制器更改为如下所示
注意,如果使用Express v5+,则不需要
try..catch
rkkpypqq2#
在fetch调用之前缺少return语句,否则不会返回任何内容