2017年4月7日金曜日

jsでfetchを使うときにContent-Typeに気をつけましょう的なお話

サーバと通信するためにはjQueryのAjaxを使えばいいんだけど、
fetchっていうものがあったりして、reactとか使ってるとfetchとか使いたくなってくる。
というかむしろjQueryを使わなくなるわけなんだけど。

で、そのfetchを使ってPOSTする時にサーバ側でPOSTデータを受け取れないってことがあった。
ということで今日はそのお話をば。

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)
})
view raw post-form.js hosted with ❤ by GitHub
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)
})
view raw post-json.js hosted with ❤ by GitHub

とりあえずapplication/jsonで送る場合と、formDataを送りたい場合を書いた。
簡潔に述べるとformDataを送りたい場合は、Content-Typeを指定してはいけないということ。
指定してしまうとboundaryがうんちゃらかんちゃらだかなんだかよくわからないことになってしまってサーバ側で処理できなくなる。
なのでこれに気をつけて記述しないとダメっていう。
確かにjQueryでもformDataを送信するときはfalseにしてたしなぁって今更思ったっていう。

というかそもそもContent-Type指定しなければいいんじゃないかって思ったり思わなかったり。
ってな感じでfetchするときには気をつけましょう的なみたいな。

0 件のコメント:

コメントを投稿

Pages (26)1234567 Next

Adsense