如果我執行 curl localhost:8080/recipes它可以作業。但是如果我在 javascript 中使用我的代碼在 firefox 出現以下錯誤:
- 跨域請求被阻止:同源策略不允許讀取位于 https://localhost:8080/recipes 的遠程資源。(原因:CORS 請求沒有成功)。狀態代碼:(空)。
- 型別錯誤:嘗試獲取資源時出現網路錯誤。

但是,如果直接使用它的 url,它會起作用:

我在 javascript 中的客戶端代碼非常簡單:
const url = 'https://localhost:8080';
const ul = document.getElementById('parrafo');
const list = document.createDocumentFragment();
const btn = document.getElementById("boton");
btn.addEventListener("click", function () {
sendData();
});
function sendData(){
fetch(url "/recipes")
.then((response) => {
return response.json();
})
.then((data) => {
let recipes = data;
recipes.map(function(recipe) {
let li = document.createElement('li');
let name = document.createElement('h2');
let id = document.createElement('span');
name.innerHTML = `${recipe.name}`;
id.innerHTML = `${recipe.id}`;
li.appendChild(name);
li.appendChild(id);
list.appendChild(li);
});
})
.catch(function(error) {
console.log(error);
});
ul.appendChild(list);
}
提前致謝
uj5u.com熱心網友回復:
您必須在客戶端使用代理或在服務器端啟用 CORS。默認情況下,CORS 禁用兩個不同埠之間的請求
uj5u.com熱心網友回復:
您正在嘗試使用“https”連接到本地主機,這會使您的請求 cors 出錯。
在 URL 中,您的請求是“HTTP”。所以改變這一行:
const url = 'http://localhost:8080';
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/402035.html
標籤:javascript 去 拿来
上一篇:找到陣列內元素的總和對?
