简体   繁体   English

如何使用 fetch 正确发送请求帖子标头?

[英]How do I correctly send request post headers using fetch?

Access to fetch at 'backend' from origin 'frontend' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response. CORS 策略已阻止从源“前端”获取“后端”的访问权限:访问控制允许标头在预检响应中不允许请求标头字段内容类型。

I continue to get this error no matter what I do in my application.无论我在我的应用程序中做什么,我都会继续收到此错误。 I am building a react + express application and I have no idea what to do anymore.我正在构建一个 react + express 应用程序,但我不知道该做什么了。

This is my backend code that has to do with cors.这是我与 cors 相关的后端代码。

app.use(cors({
    origin: "*",
    methods: 'GET,HEAD,OPTIONS,POST,PUT',
    allowedHeaders: "Origin, Content-Type, Accept"
}));
app.options('*', cors()) 
app.use(function (req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', 'frontend');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type,accept');
    next();
});

This is the frontend code using fetch that is making a post request.这是使用 fetch 发出发布请求的前端代码。

fetch('backend', {
          method: 'post',
          headers: {
            'Accept': 'application/json',
                      'Content-Type': 'application/json',
                  },
          body: JSON.stringify({
            downloadLink: link,
            password: password,
            user: true,
            apiKey: apiKey
          })

I'm so lost as theoretically there should be no problems with this.我很迷茫,理论上应该没有问题。 I have seen all the posts that people have made before and none of them work.我看过人们之前发布的所有帖子,但没有一个有效。 Any idea why?知道为什么吗? Thanks.谢谢。

EDIT: I should mention that it works perfectly on localhost.编辑:我应该提到它在本地主机上完美运行。 Just fails when going through nginx reverseproxy and cloudflare.通过 nginx reverseproxy 和 cloudflare 时失败。

EDIT: Images of network tab编辑:网络选项卡的图像ññ

好的,所以最终的工作是完全删除 app.use(cors()) 并保留 app.use (function…)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM