[英]Why fetch JavaScript in Laravel always return empty value?
我正在刀片模板視圖中從系統本身獲取 API。 但我總是返回{}
。
fetch("http://mylaravelapp.com/api/list")
.then(response => {
console.log(JSON.stringify(response));
});
I already set CORS header inside my API using this library, https://github.com/barryvdh/laravel-cors .
有幾個問題:
fetch
API 設計中的一個缺陷,更多信息請參見我的貧血小博客。 您需要檢查response.ok
。response
是一個沒有自己的可枚舉屬性的 object,因此JSON.stringify
將為它返回"{}"
。 要獲取響應,您必須通過響應對象的方法之一讀取響應正文,例如text
、 json
、 arrayBuffer
、 formData
或blob
。例如:
fetch("http://mylaravelapp.com/api/list")
.then(response => {
if (!response.ok) {
throw new Error("HTTP error " + response.status);
}
return response.text(); // or .json(), .arrayBuffer(), ...
})
.then(data => {
console.log(JSON.stringify(data));
})
.catch(error => {
console.error(error.message);
});
嘗試返回 JSON 數據並在您的 Fetch 請求中使用 JSON 數據類型
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.