2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

TypeError: Failed to execute 'fetch' on 'Window'について

Last updated at Posted at 2020-10-26

fetch apiを使おうとして躓いたのでメモ

##問題

createItems() {

  var opt = {
    "method": "POST", 
    "headers": {"Content-Type": "application/json"}, 
    "body": {
      "title": "テストタイトル",
      "content": "テストコンテンツ"
    }
  }

  fetch("/create", JSON.stringify(opt))
  .then((res) => res.json())
  .then((res) => alert("ok"))
  .catch((err) => alert(err));
    
}
TypeError: Failed to execute 'fetch' on 'Window': parameter 2 ('init') is not an object.

##解決方法
"init"はfetch関数の第2引数のことである。
見ると引数の値がobjectではなくstringになっていた。
なので正しい書き方は

fetch("/create", opt)

である。Content-Typeがjsonなのでoptもjsonにしなければいけないと勘違いしていたことが原因。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?