I keep getting CORS errors on my project:
Access to XMLHttpRequest at ‘http://127.0.0.1:8100/api/proses_api.php’ from origin ‘http://localhost:8100’ has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.
I have allowed the following headers in my API:
header(“Access-Control-Allow-Methods: PUT, GET, HEAD, POST, DELETE, OPTIONS”);
header(“Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization, x-xsrf-token”);
header(“Content-Type: application/json; charset=utf-8”);
I also used the Network Inspect tool to get the headers, but as far as I can see they are already enabled within the headers:
Any advice would be appreciated
@Spendy Where do you want to use ? Like web or actual device?
@bala975000 Right now, I am just testing on web. Won’t be moving to device for a bit. Just a basic CRUD API login system.
Sometimes this is due to a browser security issue.
To solve this you have 3 alternatives that I will mention below:
1.- In the google chrome browser download this add-on and once installed you must close the browser and open it again. once this is done activate the core icon that will appear in the upper right and rerun your code.
2.- If point 2 still does not work you have to activate on your server where you are consuming the service you want it to accept requests. Here you will have more work because it will depend on how you are publishing the service (XAMPP, IIS, etc …) and give you the Access-Control-Allow-Origin permissions:
3.- Raise an emulator and run your application in debug mode, for this you must do it with the same android studio emulator or, alternatively, with the same device. If you do it with this option, which in my opinion is the fastest and that I work with, you avoid generating and installing more things than you need.
As a reiterator, the core issue is part of the security that browsers bring and is to avoid requests for data from users without authenticity credentials.
@cristsaavedra thank you for the advice. I will try it out, I just tested by accessing localhost via 127.0.0.1 and it got rid of the CORS error but is now showing 404 errors. I have explicitly told it the server is on 127.0.0.1 and it still shows an error. Any idea?
404 error is an error of the url or the service you are trying to consume. What it tells you is that the route you are consulting does not find it or does not exist. Check the url you are consuming in your application and try again.