[英]How use no-cors with fetch()
我有個問題。 我試着解釋一下。
我的客戶要求我構建一個 web 門戶,用於在私有服務器上獲取和修改數據,使用基本身份驗證。
私有服務器返回一個 XML 文件。
我嘗試使用 fetch() 獲取數據,但出現 CORS 錯誤。 我知道那是什么意思,但我沒有私人服務器上的手。
所以我想將我的 fetch() 用於:
mode : 'no-cors'
但如果我這樣使用,我可以使用獲取的數據。
我想我有兩個主要的解決方案:
如果我無法添加 CORS 標頭,我可能想要構建一個小型服務器端腳本,它可以代表我發出這些請求。
我的腳本現在可以調用我的腳本,而不是直接調用目標,它必須在服務器端為您執行請求。
但是,如果我沒有在服務器上的手,我該怎么做呢?
如果有人有想法...
非常感謝...
- - 編輯 - - -
我的代碼:
getListApps: async function () {
let url = `${SA_BASE_URL}/applications`;
// Set headers
let headers = new Headers();
headers.append('Authorization', 'Basic ' + btoa(SA_LOGIN + ":" + SA_PASSWORD));
try {
// GET request
const response = await fetch(url, {
method: 'GET',
headers: headers,
mode: 'no-cors',
credentials: 'include' })
if (response.status === 200) {
const data = await response.json();
this.listApp = data;
this.listApp.forEach(app => {
if (app.status === "DISCONNECTED") {
this.listDecApp.push(app);
}
});
this.nbr = this.listDecApp.length;
} else {
if (response.status === 400) this.errors = ['Invalid app_permissions value. (err.400)'];
if (response.status === 401) this.errors = ['Acces denied. (err.401)'];
}
} catch (error) {
console.log(error);
this.errors = ["Une erreur est survenue lors de la récupération des informations sur le serveur."]
}
},
如果您可以使用 no-cors,請將其設置在headers中,例如:
var opts = {
headers: {
'mode':'cors'
}
}
fetch(url, opts)
如果您不控制 API,您將無能為力。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.