5
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Nuxt2=>Nuxt3の移行メモ】$fetchでFormDataをPOSTする時、Content-Typeを設定しないようにする

Last updated at Posted at 2024-02-22

現状

Nuxt2のコード例

nuxt2.ts
const formData = new FormData()
formData.append('file', myFile)

const result = await axios.post('myApi', formData)

そのままNuxt3に書き換えしたら、

nuxt3.ts
const formData = new FormData()
formData.append('file', myFile)

const result = await $fetch('myApi', {
    method: 'POST',
    body: formData
  }
)

400 Bad Requestになりました。

調査

MDNのドキュメント調べてみたら、FetchApiを使ってFormDataをPOSTしたいとき、Content-Typeは何も設定しないのが正解でした。

Warning: When using FormData to submit POST requests using XMLHttpRequest or the Fetch API with the multipart/form-data content type (e.g. when uploading files and blobs to the server), do not explicitly set the Content-Type header on the request. Doing so will prevent the browser from being able to set the Content-Type header with the boundary expression it will use to delimit form fields in the request body.

解決

デフォルトのContent-Type: "application/json; charset=UTF-8"設定しているため、FormDataを送りたいときContent-Typeを削除することにしました。

nuxt3.ts
// デフォルトのheaders設定
const opts = {
  headers: new Headers(),
}
opts.headers.set("Content-Type", "application/json; charset=UTF-8")

// FormDataを送る時onRequestの中にContent-Typeを削除
onRequest({ request, options }) {
  options.headers = opts.headers;
  if (options.body instanceof FormData) {
    options.headers.delete("Content-Type");
  }
}

これで無事POSTできるようになりました。

参考


弊社ではエンジニアを募集しています。ご興味ございましたら以下からどうぞ。

採用バナー細長2.png


5
1
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
5
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?