Fetch: POST json data

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

    I have created a thin wrapper around fetch() with many improvements if you are using a purely json REST API:

    // Small library to improve on fetch() usage
    const api = function(method, url, data, headers = {}){
      return fetch(url, {
        method: method.toUpperCase(),
        body: JSON.stringify(data),  // send it as stringified json
        credentials: api.credentials,  // to keep the session on the request
        headers: Object.assign({}, api.headers, headers)  // extend the headers
      }).then(res => res.ok ? res.json() : Promise.reject(res));
    };
    
    // Defaults that can be globally overwritten
    api.credentials = 'include';
    api.headers = {
      'csrf-token': window.csrf || '',    // only if globally set, otherwise ignored
      'Accept': 'application/json',       // receive json
      'Content-Type': 'application/json'  // send json
    };
    
    // Convenient methods
    ['get', 'post', 'put', 'delete'].forEach(method => {
      api[method] = api.bind(null, method);
    });
    

    To use it you have the variable api and 4 methods:

    api.get('/todo').then(all => { /* ... */ });
    

    And within an async function:

    const all = await api.get('/todo');
    // ...
    

    Example with jQuery:

    $('.like').on('click', async e => {
      const id = 123;  // Get it however it is better suited
    
      await api.put(`/like/${id}`, { like: true });
    
      // Whatever:
      $(e.target).addClass('active dislike').removeClass('like');
    });
    

提交回复
热议问题