概要
fetch は通信リクエストする関数。結果は Promise で扱える。
モダンブラウザはすべて対応している。
Node.js 18 では Experimental(CLIでの無効化フラグが存在する、利用時にメッセージはない)となっている。
公式ドキュメント
https://developer.mozilla.org/en-US/docs/Web/API/fetch
https://nodejs.org/dist/latest-v18.x/docs/api/globals.html#fetch
コード例
interface FetchRequest {
url: string
options: object
}
async function fetchAsync (request: FetchRequest): Promise<string> {
return await fetch(request.url, request.options)
.then(async (response) => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`)
}
return await response.blob()
})
.then(async (response) => {
return await response.text()
})
}
async function main (): Promise<void> {
const result = await fetchAsync({
url: 'https://www.google.com',
options: {}
})
console.log(result)
}
main().catch((error) => {
console.error(error)
})