You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用App Router时Fetch请求无法获取本地跨端口Express API数据

调用本地Express API返回空数组,但curl请求正常的问题

我花了一整天尝试调用后端API,始终没能成功获取到预期数据。以下是我的page.js代码:

export default async function Page() {
  //const response = await fetch('https://api.github.com/repos/vercel/next.js')
  const response = await fetch('http://localhost:5000/api/scores')

  const data = await response.json()
 
  console.log("Fetched data: ", data)

  return <h1>{data.id}</h1>;
}

注:被注释的GitHub API请求可以成功返回数据,当前请求的console.log输出为:

Fetched data: [ ]

对应的Express路由代码:

// @route GET api/scores
// @desc Get all scores
// @access Public
router.get('/', async (req, res) => {
    try {
        const scores = await Score.find().sort({ date: -1 });
        res.json(scores);
    } catch (err) {
        console.error(err.message);
        res.status(500).send('Server Error');
    }
});

我认为这不是CORS问题,因为执行以下curl命令可以正常获取数据:

curl -X GET -H "Origin: http://localhost:3000" http://localhost:5000/api/scores

curl返回结果:

[{"_id":"65e8c320bf193cd77f57b4ae","player":"65e8b96fbf193cd77f57b4aa","score":55,"date":"2024-03-06T19:25:20.096Z","__v":0},
{"_id":"65e8b977bf193cd77f57b4ac","player":"65e8b96fbf193cd77f57b4aa","score":55,"date":"2024-03-06T18:44:07.561Z","__v":0},
{"_id":"65e8b91d73915db8201681f7","player":"65e8b7d2d365d9363f20f63e","score":47,"date":"2024-03-06T18:42:37.801Z","__v":0},
{"_id":"65e8b91673915db8201681f5","player":"65e8b7d2d365d9363f20f63e","score":45,"date":"2024-03-06T18:42:30.433Z","__v":0}]

编辑补充:
调用.json()之前的Response对象输出:

Fetched response:  Response {
  [Symbol(realm)]: { settingsObject: {} },
  [Symbol(state)]: {
    aborted: false,
    rangeRequested: false,
    timingAllowPassed: false,
    requestIncludesCredentials: false,
    type: 'default',
    status: 200,
    timingInfo: null,
    cacheState: '',
    statusText: '',
    headersList: HeadersList {
      cookies: null,
      [Symbol(headers map)]: [Map],
      [Symbol(headers map sorted)]: null
    },
    urlList: [],
    body: { stream: undefined, source: [Uint8Array], length: 2 }
  },
  [Symbol(headers)]: HeadersList {
    cookies: null,
    [Symbol(headers map)]: Map(7) {
      'connection' => [Object],
      'content-length' => [Object],
      'content-type' => [Object],
      'date' => [Object],
      'etag' => [Object],
      'keep-alive' => [Object],
      'x-powered-by' => [Object]
    },
    [Symbol(headers map sorted)]: null
  }
}
Fetched data:  []

内容的提问来源于stack exchange,提问作者Lake Pry

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 08:47:07