0
2

More than 1 year has passed since last update.

TypeScript fetch 関数で通信リクエストする

Posted at

概要

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)
})
0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2