[英]Fetch data from http in js using fetch
Microsoft 365 Excel add-in
generated using yeoman generator
which I just want to fetch some data from a url
, while fetching from https
it is working fine.http
執行相同操作時,我收到一條錯誤消息TypeError: Failed to fetch
。 現在,我知道我無法從http
鏈接中獲取信息,但有辦法解決。html
文件中包含<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
。// Fetch json value
console.log(`Fetching`);
var url = "http://1<ip>:<port>/fetch_api";
//var url = "https://api.publicapis.org/entries";
const response = await fetch(url, {
method: 'GET',
headers: {
accept: 'application/json',
},
});
if (!response.ok) {
throw new Error(`Error! status: ${response.status}`);
}
const result = await response.json();
console.log(result);
首先,您在標題字典headers: { 'Content-Type': 'application/json' }
然后記住這個 function 必須是異步的。
無需編寫那么多代碼來使用 fetch 獲取請求。 獲取請求是默認方法。 你可以只寫 fetch(URL)。 對於另一種類型的請求,您應該編寫方法、標頭、正文等。
只需編寫此 function 並調用它。
async function getData () {
const URL = 'your_url'
let response = await fetch(URL)
let data = await response.json()
console.log(data)
}
我正在使用異步等待來獲取數據。 對於任何類型的 promise 請求,您應該使用異步等待,這將幫助您處理承諾。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.