简体   繁体   中英

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.

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.

This is my backend code that has to do with 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('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.

EDIT: Images of network tabññ

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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