I know this has been addressed a lot of times on SO, but all the answers are mostly in the vein of "add a certain header to the server". In this case, the API (Shopify) works perfectly fine and can easily be accessed via curl.
I've tried this both with the Axios library and the Fetch API.
- I've tried every value for
referrer
,mode
, andreferrerPolicy
in the Fetch options. - I've confirmed my BasicAuth credentials are correct.
- I've tried in multiple browsers.
- I've tried from both localhost, localhost.com (set the value in my /etc/hosts), and from a server with a real domain name.
I can't understand why this would work perfectly fine in cURL, but not with fetch().
Here's a shortened version of my code:
const apiKey = 'mykey';
const apiPassword = 'mypass';
const apibase = 'https://my-shop-domain.myshopify.com/admin/';
const endpoint = 'locations.json';
var headers = new Headers({
"Authorization": "Basic " + btoa( apiKey + ':' + apiPassword ),
});
fetch( apibase + endpoint {
method: 'GET',
headers: headers,
mode: 'no-cors',
// cache: "no-store",
// referrer: "client",
// referrerPolicy: "origin",
// credentials: 'include'
}).then( resp => resp.json().then( resp => {
console.log( resp );
})).catch( err => {
console.error(err);
});
and the error that returns is
Access to fetch at 'https://my-shop-domain.myshopify.com/admin/locations.json' from origin 'https://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
If Shopify doesn't include the Access-Control-Allow-Origin header, why does the request work fine with cURL? There are node libraries and Ruby libraries to access the Shopify API, so it's hard to believe that they simply don't allow access from javascript at all.
So I guess my question is what can I do to access this API from with javascript?
-i
option, and it works fine. I added Origin header as so:curl -i -X GET -H "Authorization:Basic abcde12345" 'https://my-store.myshopify.com/admin/locations.json' -H "Origin:localhost"
and it still worked fine.Access-Control-Allow-Origin
header. cURL does not run such a check neither any other server-side software(e.g. NodeJS or Tomcat) does.gmail.com/account
, and if you were logged in to gmail then they'd get to see your account page. CORS blocks this. (What I don't understand, though, is why browsers don't just not send cookies along with CORS-disallowed requests. Why disable the whole request altogether?)