サーバと通信するためにはjQueryのAjaxを使えばいいんだけど、
fetchっていうものがあったりして、reactとか使ってるとfetchとか使いたくなってくる。
というかむしろjQueryを使わなくなるわけなんだけど。
で、そのfetchを使ってPOSTする時にサーバ側でPOSTデータを受け取れないってことがあった。
ということで今日はそのお話をば。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const formData = new FormData() | |
formData.append("hoge","hogehoge") | |
formData.append("foo","bar") | |
fetch("url", { | |
headers:{ | |
'Accept': 'application/json, */*', | |
//'Content-type':'application/json' | |
}, | |
method:"post", | |
body:formData | |
}) | |
.then(response => { | |
return response.json().then(json => ({ | |
status: response.status, | |
json })) | |
}) | |
.then(({ | |
status, | |
json | |
}) => { | |
if (callback) callback(status, json) | |
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fetch("url", { | |
headers:{ | |
'Accept': 'application/json, */*', | |
'Content-type':'application/json' | |
}, | |
method:"post", | |
body:JSON.stringify({hoge:"hogehoge",foo:"bar"}) | |
}) | |
.then(response => { | |
return response.json().then(json => ({ | |
status: response.status, | |
json })) | |
}) | |
.then(({ | |
status, | |
json | |
}) => { | |
if (callback) callback(status, json) | |
}) |
とりあえずapplication/jsonで送る場合と、formDataを送りたい場合を書いた。
簡潔に述べるとformDataを送りたい場合は、Content-Typeを指定してはいけないということ。
指定してしまうとboundaryがうんちゃらかんちゃらだかなんだかよくわからないことになってしまってサーバ側で処理できなくなる。
なのでこれに気をつけて記述しないとダメっていう。
確かにjQueryでもformDataを送信するときはfalseにしてたしなぁって今更思ったっていう。
というかそもそもContent-Type指定しなければいいんじゃないかって思ったり思わなかったり。
ってな感じでfetchするときには気をつけましょう的なみたいな。
0 件のコメント:
コメントを投稿