CORS
当您尝试从另一个域的一个域访问资源时,会发生 CORS 错误。它只发生在浏览器中,是一项安全功能。
所以本质上,当您在localhost:3000 上从https://superheroapi.com/api/1 获取数据时,浏览器首先会询问superheroapi.com,“嘿,这个域可以从你那里获取数据吗?”。 superheroapi.com 然后会说,“我只接受来自这些域的请求”。如果localhost:3000 不在该列表中,您将收到 CORS 错误。
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
您可以通过Access-Control-Allow-Origin 标头更改superheroapi.com 接受的域。您可以手动完成,或者有一个方便的 npm 包可以在 Next.js 中为您处理。
修复 Next.js 中的 CORS
默认情况下,在 Next.js 中,CORS 标头仅限于同域流量。但是,您可以更改此设置。
Next.js 实际上在他们的文档中有一个关于向 api 路由添加 CORS 标头的指南。
https://nextjs.org/docs/api-routes/api-middlewares#connectexpress-middleware-support
不过,简而言之,首先安装 CORS 包。
npm i cors
# or
yarn add cors
# or
pnpm add cors
然后将其添加到 API 路由中。
import Cors from 'cors'
// Initializing the cors middleware
const cors = Cors({
methods: ['GET', 'HEAD'],
})
// Helper method to wait for a middleware to execute before continuing
// And to throw an error when an error happens in a middleware
function runMiddleware(req, res, fn) {
return new Promise((resolve, reject) => {
fn(req, res, (result) => {
if (result instanceof Error) {
return reject(result)
}
return resolve(result)
})
})
}
async function handler(req, res) {
// Run the middleware
await runMiddleware(req, res, cors)
// Rest of the API logic
res.json({ message: 'Hello Everyone!' })
}
export default handler
代码 sn-ps 取自 Next.js 文档。所有功劳都归功于 Next.js 的制作者。