DEV Community

Cover image for How to troubleshoot CORS Preflight / Options errors in 2022

Posted on


How to troubleshoot CORS Preflight / Options errors in 2022


Reference this original flow chart I created for this post.

Introduction: What is CORS? What is preflight? What is the Options method?

The CORS stands for the Cross-Origin Resource Sharing. It matters when a currently viewed website is trying to fetch a resource like JSON from another web server (cross-origin) because browsers restrict cross-origin HTTP requests initiated from scripts.

As a safety precaution, before sending the original request, browsers send a cross-origin server a so-called preflight request whose headers include both the HTTP method and headers that will be used in the original request. The preflight request uses the HTTP OPTIONS method.

For more precise definitions and related discussions, The official document is the best.

The rest of this post discusses common situational questions and answers to solve them.

Question 1: Options request is sent to the backend dev-server, but the response status code is 405 (Method Not Allowed). What should the frontend do to resolve the issue?

Cross-Origin Request Blocked: The Same Origin Policy disallows
reading the remote resource at (Reason: XXX).
Enter fullscreen mode Exit fullscreen mode

Answer 1

You can adopt one of the two choices below.

  1. Ask the backend to handle the option method. A preflight request is inevitable and appropriate for security reasons in some situations.

  2. Consider the possibility of switching from a preflight request to a simple request. Simple requests don't trigger a CORS preflight.

To make your request simple, you need to satisfy all of the conditions written here.

Question 2: The backend-dev team prepared a server stub auto-generated by Swagger Codegen for our frontend-dev team. But I see some CORS errors related to the options method.

Answer 2

You can adopt one of the last three choices below.

  1. (Don't✋) Modify the server stub implementation manually. It would be a poor choice because a server stub can no longer be auto-generated.

  2. Suppose that your app is made from Vue or React. Then, use framework built-in proxy features such as the React Dev Server Proxy (See this post) or Vue Proxy

  3. Use a general proxy tool like CORS Anywhere. This proxy manipulates the request header to temporarily circumvent the CORS protection.

  4. Use a browser extension such as Allow CORS

Top comments (0)