Fetch: POST json data

后端 未结 13 1724
小蘑菇
小蘑菇 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:06

    From search engines, I ended up on this topic for non-json posting data with fetch, so thought I would add this.

    For non-json you don't have to use form data. You can simply set the Content-Type header to application/x-www-form-urlencoded and use a string:

    fetch('url here', {
        method: 'POST',
        headers: {'Content-Type':'application/x-www-form-urlencoded'}, // this line is important, if this content-type is not set it wont work
        body: 'foo=bar&blah=1'
    });
    

    An alternative way to build that body string, rather then typing it out as I did above, is to use libraries. For instance the stringify function from query-string or qs packages. So using this it would look like:

    import queryString from 'query-string'; // import the queryString class
    
    fetch('url here', {
        method: 'POST',
        headers: {'Content-Type':'application/x-www-form-urlencoded'}, // this line is important, if this content-type is not set it wont work
        body: queryString.stringify({for:'bar', blah:1}) //use the stringify object of the queryString class
    });
    

提交回复
热议问题