我目前正在使用我的第一个较大的 NextJS 应用程序,并遇到了经典的 CORS 问题。
我的后端托管在不同的服务器/url 上,我从这个后端获取我的 json 数据。我的前端是使用 NextJS 编写的,并部署在 Vercel 上。
我知道,我必须在后端和前端两侧都启用 CORS,在我的本地主机开发中,一切正常(甚至从后端获取数据)
我已经按照此指南:https://vercel.com/knowledge/how-to-enable-cors,启用了我的 NextJS 应用程序中的 CORS。我修改了 nextjs 配置:
module.exports = {
async headers() {
return [
{
source: "/.*",
headers: [
{ key: "Access-Control-Allow-Credentials", value: "true" },
{ key: "Access-Control-Allow-Origin", value: "*" },
{ key: "Access-Control-Allow-Methods", value: "GET,OPTIONS,PATCH,DELETE,POST,PUT" },
{ key: "Access-Control-Allow-Headers", value: "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version" },
]
}
]
}
};
然而,当我将应用部署到 Vercel 上时,出现以下错误:
Access to fetch at 'https://<my-censored-backend-url>' from origin 'https://<my-frontend-url>.vercel.app' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
在我的后端(使用rails编写),我已经配置了vercel上的前端允许CORS。
你们有没有在CORS方面的经验,从不同的服务器获取NextJS数据?我正在使用getStaticProps、getServerSideProps和SWR进行获取。
如果有任何帮助,将不胜感激。
'Access-Control-Allow-Origin'
头部? - juliomalves