I am currently trying to send data to an API on a subdomain, but it is failing.
In devtools I can see there is a CORS error relating to a redirect:
Access to XMLHttpRequest at 'https://api.example.com/v1/dashboard/images/upload.php' from origin 'https://example.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.
I assume the redirect is caused by lack of credentials even though I have withCredentials
on my xhr object:
let endpoint = form.action,
xhr = new XMLHttpRequest();
xhr.open('POST', endpoint);
xhr.withCredentials = true;
xhr.upload.addEventListener('progress', ({loaded, total}) => {
... stuff here ...
});
let data = new FormData(form);
xhr.send(data);
My API has these headers set in the Nginx config:
add_header "Access-Control-Allow-Origin" "https://example.com" always;
add_header "Access-Control-Allow-Credentials" "true";
Other APIs in use work fine but use fetch
rather than XHR
– the reason for using XHR for this request is I want to feedback to the user upload progress, which I understand isn’t a feature of fetch
?