为什么我的GET请求在Node中使用Fetch [closed]挂起

rmbxnbpk  于 2023-10-17  发布在  Node.js
关注(0)|答案(2)|浏览(193)

**已关闭。**此问题需要debugging details。它目前不接受回答。

编辑问题以包括desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem。这将帮助其他人回答这个问题。
5天前关闭。
Improve this question
getDocuments请求从未完成/保持挂起。我错过了什么?
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上:

mtb9vblg

mtb9vblg1#

假设像这样将getDocuments添加到/api路由器

router.get("/getDocuments", getDocuments);

Express不使用路由处理程序的返回值。相反,您需要发送一个响应。
您需要将控制器更改为如下所示

exports.getDocuments = async (req, res, next) => {
  console.log("getting documents...");

  const url = "EXTERNAL API ENDPOINT";
  try {
    const response = await fetch(url, {
      headers: {
        "x-api-key": "KEY",
      },
    });

    if (!res.ok) {
      // log details of unsuccessful responses
      console.error(
        "Fetch failed",
        url,
        response.status,
        await response.text(),
      );
      throw new Error("Failed to fetch from upstream");
    }

    // 👇 👇 👇 
    res.json(await response.json()); // send a response
    // 👆 👆 👆

  } catch (err) {
    // propagate the error to Express' error handlers
    next(err);
  }
};

注意,如果使用Express v5+,则不需要try..catch

rkkpypqq

rkkpypqq2#

在fetch调用之前缺少return语句,否则不会返回任何内容

相关问题