How to resolve 'preflight is invalid (redirect)' in CORS

匿名 (未验证) 提交于 2019-12-03 01:48:02

问题:

I have followed this step to setup my server to enable CORS. https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api

But now in my browser dev console, I see this error message:

XMLHttpRequest cannot load https://serveraddress/abc. Response for preflight is invalid (redirect)

Do you know what can I do to fix it? I am making a CORS request in HTTPS. I think that is causing the 'preflight is invalid (redirect)' failure. But I don't know why or what is redirecting the OPTIONS request.

Thank you.

回答1:

Your code’s causing your browser to send a CORS preflight OPTIONS request that does a redirect.

Browsers currently refuse to follow the redirect in that case, because the CORS spec previously required browser to do that. The restriction is actually no longer in the spec, but browsers need to update their implementations to match the spec change.

You may be able to adjust your code to avoid triggering the browser to send the OPTIONS request.

As far as what all is going on for this case, the first thing to note is, browsers do a CORS preflight if:

  • the request method is anything than GET, HEAD, or POST
  • you’ve set custom request headers other than Accept, Accept-Language, Content-Language, Content-Type, DPR, Downlink, Save-Data, Viewport-Width, or Width
  • the Content-Type request header has a value other than application/x-www-form-urlencoded, multipart/form-data, or text/plain

If you can’t change your code to avoid need for browsers to do a preflight, then another option is:

  1. Examine the response and see what URL the server is redirecting to after the OPTIONS.
  2. Change your code to make the request to that other URL directly instead.

See the answer at CORS request with Preflight and redirect: disallowed. Workarounds? for details on possible workaround.

Also as noted there, the restriction on browsers not following redirects for CORS preflights is no longer in the spec, but browsers need to update their implementations to match the spec change.



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!