Fetch: POST json data

后端 未结 13 1767
小蘑菇
小蘑菇 2020-11-22 03:25

I\'m trying to POST a JSON object using fetch.

From what I can understand, I need to attach a stringified object to the body of the request, e.g.:



        
13条回答
  •  野的像风
    2020-11-22 04:19

    This is related to Content-Type. As you might have noticed from other discussions and answers to this question some people were able to solve it by setting Content-Type: 'application/json'. Unfortunately in my case it didn't work, my POST request was still empty on the server side.

    However, if you try with jQuery's $.post() and it's working, the reason is probably because of jQuery using Content-Type: 'x-www-form-urlencoded' instead of application/json.

    data = Object.keys(data).map(key => encodeURIComponent(key) + '=' + encodeURIComponent(data[key])).join('&')
    fetch('/api/', {
        method: 'post', 
        credentials: "include", 
        body: data, 
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    })
    

提交回复
热议问题