Fetch: POST json data

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

    I think that, we don't need parse the JSON object into a string, if the remote server accepts json into they request, just run:

    const request = await fetch ('/echo/json', {
      headers: {
        'Content-type': 'application/json'
      },
      method: 'POST',
      body: { a: 1, b: 2 }
    });
    

    Such as the curl request

    curl -v -X POST -H 'Content-Type: application/json' -d '@data.json' '/echo/json'
    

    In case to the remote serve not accept a json file as the body, just send a dataForm:

    const data =  new FormData ();
    data.append ('a', 1);
    data.append ('b', 2);
    
    const request = await fetch ('/echo/form', {
      headers: {
        'Content-type': 'application/x-www-form-urlencoded'
      },
      method: 'POST',
      body: data
    });
    

    Such as the curl request

    curl -v -X POST -H 'Content-type: application/x-www-form-urlencoded' -d '@data.txt' '/echo/form'
    

提交回复
热议问题