[英]Fix 'cors' request between different localhosts. 405 (Method Not Allowed)
我使用以下代碼來請求文件:
function getData(imageEndpoint) {
return fetch(imageEndpoint, {
mode: 'cors'
})
.then(response => {
console.log(response);
})
.then(data => {
if (!('caches' in window)) {
return caches.open(cacheName)
.then(cache => {
return cache.put(imageEndpoint, data);
});
}
return data;
})
.catch(e => {
console.log('Request issue, ', e);
});
}
在以下錯誤消息中輸出:
Failed to load http://localhost:7000/image.jpg: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
PS服務器工作:8000
當我添加cors標頭時
return fetch(imageEndpoint, {
mode: 'cors',
headers: {
'Access-Control-Allow-Origin': '*'
}
})
引發以下錯誤:
http://localhost:7000/image.jpg 405 (Method Not Allowed)
index.html:1 Failed to load http://localhost:7000/image.jpg: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. The response had HTTP status code 405. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
您能否建議如何設置請求才能成功接收文件?
您必須在OPTIONS響應和POST響應上都具有標頭Access-Control-Allow-Origin: URL Here
或Access-Control-Allow-Origin:*。 您還應該在POST響應中包含標頭Access-Control-Allow-Credentials:true。
您的OPTIONS響應還應該包含標頭Access-Control-Allow-Headers:origin,content-type,accept以匹配請求的標頭。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.