0
I have a problem in a study project, I gave a "googlada" and learned that whenever I make a first request defining headers for an Api, this request will be as OPTIONS, so that the browser receives the headers that the Api supports, however I want to know how to deal with this security.
What I’m trying to do is send a header in a GET request, with the key, "Authorization", and value being my authorization token, but when this request arrives at the server it is converted into OPTIONS, and my header is not recognized, it arrives at the api like this "Access-Control-Request-Headers: Authorization", I am using Reactjs with Axios, and in the backend PHP Codeigniter with this API library https://github.com/ctechhindi/CodeIgniter-API-Controller.
So I thought if I should save the response of the first request so that my browser understands that it has already been executed and successful, remembering that in the backend I set the following already:
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Authorization");
Did you ever catch an error in the browser console? If so, could you post here? Another point, your request is not converted to the OPTIONS method, the browser is the one who makes this preflight request to check if the API can be consumed. Your api must be prepared to receive this type of request and perform the appropriate validations. More details: https://developer.mozilla.org/en-US/docs/Web/HTTP/Controle_Acesso_CORS
– Marcelo Vismari
Hi Marcelo, first thank you for taking the time to help me, and yes I had errors on the console, this: "Access to Xmlhttprequest at http://localhost/meuprojeto/index.php/api/validar-token' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: It does not have HTTP ok status."
– Jorge Otávio
"OPTIONS http://localhost/Rapid-os-api/index.php/api/validate-token 401 (Unauthorized)" this error also
– Jorge Otávio
Jorge, apparently your API is not responding to the request with the OPTIONS method. Have a look at the following link and if you do not resolve please comment again: https://stackoverflow.com/questions/44479681/cors-php-response-to-preflight-request-doesnt-pass-am-wing-origin
– Marcelo Vismari
Just to complement, if your api does not respond to the OPTIONS request the browser will not perform your request (e.g., GET/POST),
– Marcelo Vismari
Thanks Marcelo for helping, I managed to solve with your tips, if you want to elaborate the answer I will vote on it to complete the topic.
– Jorge Otávio