Skip to content
Advertisement

how to get data use fetch API correctly in vue js?

I’m trying to fetch data from the backend using the GET method, but I always fail to get the data. I get the following error: CORS header ‘Access-Control-Allow-Origin’ missing. I don’t know how it happens because I tried to use POST method to my backend it worked.

Here’s a capture of my browser tools

enter image description here

When I use fetch to get data it always sends 2 requests, first a OPTIONS then a GET. After every request I get this error, then I try to resend request through browser tools, and it works without errors.

Here’s my code:

JavaScript

Thanks in advance

Advertisement

Answer

Your backend application runs on a different domain than your client application? That causes the CORS header ‘Access-Control-Allow-Origin’ missing error because basically your client-side is not authorized to access your backend using its domain. Add cors headers in your first middleware in the backend. you can set a header of

JavaScript

to allow any origin to access the backend.

Or setting your specific domain to allow only it to access your backend.

JavaScript

Where https://example.com is the domain of your client side application.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement