我已經構建了 php api 來交換資料,但它會導致我的 Web 應用程式出現 CORS 問題。它在郵遞員請求上回傳正確的資料,但不在網路應用程式上回傳。

我嘗試在后端添加以下代碼
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header("Access-Control-Allow-Credentials: true");
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');

但它給了我同樣的錯誤資訊。
以下是郵遞員回復的標題。

標頭包含郵遞員回應中的 CORS 設定,但仍然無法正常作業。有沒有其他方法可以修復它?
我嘗試了幾種請求資料的方法
1.
axios.get("localhost:1234/getSingersJson.php?test=[144]")
var url = "localhost:1234/getSingersJson.php";
var params = "[144]";
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function(){
console.log(this.responseText);
}
xmlhttp.open("GET", url "?test=" params);
xmlhttp.send();
fetch(url "?test=" params)
.then(response => {
if(!response.ok) {
throw Error(response.statusText);
}
console.log(response)
})
每個代碼的確切錯誤訊息如下所示。
function api_test(){
var url = "https://localhost:1234/getSingersJson.php";
var params = "[144]";
fetch(url "?test=" params)
.then(response => {
if(!response.ok) {
throw Error(response.statusText);
}
console.log(response)
})
}

function api_test(){
var url = "https://localhost:1234/getSingersJson.php";
var params = "[144]";
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function(){
console.log(this.responseText);
}
xmlhttp.open("GET", url "?test=" params);
xmlhttp.send();
}

開發者工具中的網路選項卡如下。

請求選項卡和回應選項卡什么也不顯示。
以前我在我的本地測驗服務器上運行它。我在我的 AWS 服務器上上傳了 php 檔案,它作業正常。
uj5u.com熱心網友回復:
嘗試使用憑據發送您的 XHR 請求?
axios.get('your api url', {withCredentials: true});
withCredentials() 使您的瀏覽器在您的 XHR 請求中包含 cookie 和身份驗證標頭。如果您的服務依賴于 cookie(包括會話 cookie),則它只能使用此選項。
uj5u.com熱心網友回復:
您Origin的主機名和埠似乎與請求目標相同,只是協議不同(HTTP 與 HTTPS)。
因此,如果您通過 HTTPS 訪問您的頁面(就像您嘗試通過 HTTPS 訪問 AJAX 請求一樣),或者通過 HTTP 訪問 AJAX(就像您的頁面一樣),那么這個請求實際上根本不需要受 CORS 的約束.
一旦主頁和 AJAX URL 的協議、主機名/域和埠相同,它們就被認為是“同源”,因此CORS(跨源資源共享)限制不適用。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/342451.html
上一篇:檢測來自ajax函式的成功回應
下一篇:將資訊從AJAX傳遞到控制器類
