【发布时间】:2022-01-18 01:38:50
【问题描述】:
我使用 netlify 作为前端,使用 Heroku 和 Next.js 作为后端
在前端我发送一个这样的获取请求:
fetch(`https://backendname.herokuapp.com/data`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({"category":"_main"})
}).then(...);
在我的pages/api/data.js 后端:
export default function handler(req, res) {
req.body=JSON.parse(req.body);
res.setHeader("Access-Control-Allow-Origin", "https://frontendname.netlify.app/");
res.setHeader('Access-Control-Allow-Methods', 'POST');
res.setHeader(
'Access-Control-Allow-Headers',
'X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version'
)
if(req.method!='POST')
return res.end();
res.json({...})
}
我什至在我的 next.config.js 中添加了this:
module.exports = {
async headers() {
return [
{
// matching all API routes
source: "/api/:path*",
headers: [
{ key: "Access-Control-Allow-Credentials", value: "true" },
{ key: "Access-Control-Allow-Origin", value: "https://frontendname.netlify.app/" },
{ 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" },
]
}
]
},
reactStrictMode: true,
}
但我收到此错误:
从 'https://backendname.herokuapp.com/data' 获取获取权限 来源“https://frontendname.netlify.app”已被 CORS 阻止 策略:对预检请求的响应未通过访问控制 检查:没有“Access-Control-Allow-Origin”标头出现在 请求的资源。如果不透明的响应满足您的需求,请将 请求模式为“no-cors”以获取禁用 CORS 的资源。
我正在尝试不使用任何第三方软件包,例如 this 问题
【问题讨论】:
标签: javascript heroku next.js cors netlify