[Vuejs]-Laravel VueJS, Axios can't see CORS header but Postman and Browser do

0đź‘Ť

Thanks to apokryfos (see comments under my question) I came up with the answer. I wasn’t easy and I am still not sure if this is a way to go.

I hope this will help other people.

So first I looked at THIS post.

THE ACTUAL PROBLEM I HAD

The real problem was not setting CORS which was done correctly from the very beginning.

The real problem was that chrome was not sending the CORS preflight request.
What is a preflight request? Good question. I will answer that soon.

THE SOLUTION I MANAGED TO FIND

Let’s start with understanding what CORS PREFLIGHT REQUEST really is.

A CORS preflight request is a CORS request that checks to see if the
CORS protocol is understood and a server is aware using specific
methods and headers.

It is an OPTIONS request, using three HTTP request headers:
Access-Control-Request-Method, Access-Control-Request-Headers, and the
Origin header.

A preflight request is automatically issued by a browser and in normal
cases, front-end developers don’t need to craft such requests
themselves. It appears when request is qualified as “to be
preflighted” and omited for simple requests.

So normally browser will ommit OPTIONS CORS preflight request for SIMPLE REQUESTS.

Now my current development environment (and maybe production one once I will finish my work on that system) has npm run dev running on localhost:8081 and my Laravel backend API is running on Docker on localhost:8080

This is why I am always going to need a CORS PREFLIGHT request. I am always going to need that request because at least for the development I will always have my backend and frontend app in conflict with CORS policy.

CONCLUSION

I am still not sure if it is the correct way to go about it but it kinda makes sense. At least I am not blocked anymore with my work.

Of course, CORS settings I have in my questions will be changed to more secure once I am done. I don’t think it’s a good idea to allow anything from anywhere!

👤Robert

-4đź‘Ť

I had got the same CORS error while working on a Vue.js project. You can resolve this by disabling the security settings of your browser (eg, CHROME) for accessing cross origin apis. This solution worked perfectly for me. This solution does not require any mock server or a proxy server to be built.

You can disable the CHROME security settings for accessing apis out of the origin by typing the below command on the mac terminal:

/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome –user-data-dir=”/tmp/chrome_dev_session” –disable-web-security

After running the above command on your terminal, a new chrome window with security settings disabled will pop up. Now, run your program (npm run serve or npm run dev) again and this time you will not get any CORS error and would be able to GET request using axios.

Hope this helps!

👤skate_23

Leave a comment