The following error is from the Network section of firefox:
I've tried solving the above error by adding a headers
(based on various answers from similar problems) property in the native fetch
function when sending a React API request (or a native ES6 request for that matter).
fetch('API_ENDPOINT', // API_ENDPOINT is a different sub-domain
{
method: 'POST',
headers: {
'Authorization' : 'Basic XXXXXXXXXX'
},
body: JSON.stringify(body)
}
).then(...);
Removing the headers
section allows the request to go through (I have validated this by returning a custom message in the response header
) but I need this to add the Authorization header because I authenticate the request via the Basic token (I will migrate to Bearer soon but the same approach will be used). It looks like the initial set of headers are being replaced once I've added the headers
property?
Note: I have an .htaccess
that allows cross-origin request with definition:
<IfModule mod_headers.c>
Header add Access-Control-Allow-Methods "PUT,GET,POST,DELETE,OPTIONS"
Header add Access-Control-Allow-Credentials "true"
Header add Access-Control-Allow-Headers "Content-Type, Authorization, Access-Control-Allow-Credentials, Access-Control-Allow-Origin, Access-Control-Allow-Methods"
Header add Access-Control-Allow-Origin "*"
</IfModule>
SOLVED:
This has been solved by implementing this answer: https://stackoverflow.com/a/42558499/335547
- The
credentials
should be included asfetch
property so the Authorization header will be considered in the preflight validation. - The API should use
Access-Control-Allow-Origin
with specific source host, not"*"
- The API should use of
Access-Control-Allow-Credentials "true"