Fetch: POST json data

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

    You only need to check if response is ok coz the call not returning anything.

    var json = {
        json: JSON.stringify({
            a: 1,
            b: 2
        }),
        delay: 3
    };
    
    fetch('/echo/json/', {
        method: 'post',
        headers: {
            'Accept': 'application/json, text/plain, */*',
            'Content-Type': 'application/json'
        },
        body: 'json=' + encodeURIComponent(JSON.stringify(json.json)) + '&delay=' + json.delay
    })
    .then((response) => {if(response.ok){alert("the call works ok")}})
    .catch (function (error) {
        console.log('Request failed', error);
    });    
    

提交回复
热议问题