获取请求未从使用 App Router 在不同端口上的本地主机上运行的 Express API 中提取

问题描述 投票:0回答:1

我一整天都在尝试(未成功)尝试对我的后端 API 进行 fetch 调用。

这是我的

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>;
}

请注意,注释掉的 fetch 命令确实返回成功。

console.log
输出:

Fetched data: [ ]

这是我想要到达的快速路线:

// @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 -X GET -H "Origin: http://localhost:3000" http://localhost:5000/api/scores

[{"_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() 之前响应的输出:

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:  []
mongodb express next.js localhost fetch-api
1个回答
0
投票

没有数据时,获取响应会缓存在本地。

修复:

const response = await fetch('http://localhost:5000/api/scores', { cache: "no-store" })
© www.soinside.com 2019 - 2024. All rights reserved.