我知道这个问题已经得到解决lotSO 上的次数,但所有答案大多都是“向服务器添加某个标头”。在这种情况下,API(Shopify)工作得非常好,并且可以通过curl轻松访问。
我已经使用 Axios 库和 Fetch API 尝试过此操作。
- 我已经尝试过每个值
referrer
, mode
, and referrerPolicy
在获取选项中。
- 我已确认我的 BasicAuth 凭据正确。
- 我在多个浏览器中尝试过。
- 我已经尝试从 localhost、localhost.com(在我的 /etc/hosts 中设置值)和具有真实域名的服务器进行尝试。
我不明白为什么这在 cURL 中工作得很好,但在 fetch() 中却不行。
这是我的代码的缩短版本:
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);
});
返回的错误是
访问 ' 获取https://my-shop-domain.myshopify.com/admin/locations.json https://my-shop-domain.myshopify.com/admin/locations.json'从原点'https://本地主机:8080 https://localhost:8080' 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。如果不透明响应满足您的需求,请将请求模式设置为“no-cors”以在禁用 CORS 的情况下获取资源。
如果 Shopify 不包含访问控制允许来源header,为什么请求使用 cURL 可以正常工作?有节点库和 Ruby 库可以访问 Shopify API,因此很难相信它们根本不允许通过 JavaScript 进行访问。
所以我想我的问题是我可以做什么来使用 javascript 访问这个 API?