I have been searching for an answer to what seems like a very basic problem. I am attempting to make a cross origin HTTP request on a local host using Axios within the React framework. The server side runs on a CodeIgniter framework and uses chriskacerguis's codeigniter-restserver. I have configured an .htaccess file to set Access-Control-Allow-Origin to '*'.
My GET requests work without any issue. The problem arises when I attempt to make a POST request. I have tried using both fetch() and Axios. I get this error message in Chrome's console:
OPTIONS http://localhost/api/login 401 (Unauthorized)
(...)
localhost/:1 Access to XMLHttpRequest at 'http://localhost/api/login' 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.
I am confident that the server side code works since I am capable of making successful POST requests using Insomnia. Although I have read on many forums that a 401 error is not related to a CORS issue, it seems to me like it has to be CORS-related since my HTTP requests work in Insomnia.
After many attempts at changing the headers and different configuration options, here is the code I have on the client side:
axios.post(api_url+'login', {
headers: {
'accept': 'application/json',
'content-type': 'application/json',
},
data: {
email: this.state.email,
password: this.state.password
},
crossDomain: true,
withCredentials: true,
auth: {
username: 'admin',
password: '1234'
}
})
.then(res => {
console.log(res);
})
.catch(err => {
console.log(err);
});
}
It seems to me as though the 401 is returned on the initial OPTIONS request. I do not understand why this is happening since I've come to understand that the OPTIONS request should not required authentification. I am also capable of completing an OPTIONS request in Insomnia without any issue.
This is my first attempt at building both a REST API and a React app. I have spent many hours trying to make this basic request work and I've come to the conclusion that there must be something very obvious that I'm missing... many thanks for reading and commenting.