概念
- 和瀏覽器一樣,Deno實(shí)現(xiàn)了fetch.等Web標(biāo)準(zhǔn)API。
- Deno默認(rèn)情況下是安全的,這意味著必須顯式授予訪問(wèn)網(wǎng)絡(luò)的權(quán)限。
- 另見(jiàn):Deno的permissions模型。
概覽
在構(gòu)建任何類型的Web應(yīng)用程序時(shí),開(kāi)發(fā)人員通常都需要從Web上的其他地方檢索數(shù)據(jù)。這在Deno中的工作方式與在任何其他JavaScript應(yīng)用程序中沒(méi)有什么不同,只需調(diào)用fetch()方法即可。有關(guān)獲取的更多信息,請(qǐng)閱讀mdn documentation.。
在運(yùn)行通過(guò)Web進(jìn)行調(diào)用的腳本時(shí),Deno會(huì)出現(xiàn)異常。DENO默認(rèn)情況下是安全的,這意味著禁止訪問(wèn)IO(輸入/輸出)。要通過(guò)網(wǎng)絡(luò)打電話,必須明確告知Deno這樣做是可以的。這是通過(guò)在“deno run”命令中添加“--allow-net”命令來(lái)實(shí)現(xiàn)的。
例子
Command: deno run --allow-net fetch.ts
/**
* Output: JSON Data
*/
const json = fetch("https://api.github.com/users/denoland");
json.then((response) => {
return response.json();
}).then((jsonData) => {
console.log(jsonData);
});
/**
* Output: HTML Data
*/
const text = fetch("https://deno.land/");
text.then((response) => {
return response.text();
}).then((textData) => {
console.log(textData);
});
/**
* Output: Error Message
*/
const error = fetch("https://does.not.exist/");
error.catch((error) => console.log(error.message));