Fetch: POST json data

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

    Had the same issue - no body was sent from a client to a server.

    Adding Content-Type header solved it for me:

    var headers = new Headers();
    
    headers.append('Accept', 'application/json'); // This one is enough for GET requests
    headers.append('Content-Type', 'application/json'); // This one sends body
    
    return fetch('/some/endpoint', {
        method: 'POST',
        mode: 'same-origin',
        credentials: 'include',
        redirect: 'follow',
        headers: headers,
        body: JSON.stringify({
            name: 'John',
            surname: 'Doe'
        }),
    }).then(resp => {
        ...
    }).catch(err => {
       ...
    })
    

提交回复
热议问题