Search code examples
javascriptjsonxmlhttprequest

fetch() just doesn't send JSON object


I send JSON object using fetch() this way:

    async testPost(){
        const url = 'https://untitled-0clyb6aowq2u.runkit.sh';
        var payload = { "test" : 1 };
        const settings = {
            method: 'POST',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
                body: JSON.stringify(payload)
            }
        };
        try {
            const resp = await fetch(url, settings);
            const data = await resp.json();
            if(data.ok != 1){
                console.log('FATAL ERROR PIZDEC: ');
                console.log(data);
                return { ok: 0, error: data};
            }
            console.log('Success:' + data.success);
            return;
        }
        catch (e) {
            return { ok: 0, error: e };
        }
    }

Server always gets the request, but there's just an empty object in the body. I've tried:

  1. To use runkit as a server [fail]
  2. To use express on localhost as a server [fail]
  3. Check endpoints with the same request made from Postman. It works, postman sends normal json {"test" : 1}, it is printed in server console. So I conclude that the problem is on the client's side.
  4. Check all the headers and CORS policy [doesn't help]
  5. Use different approaches to send request: jQuerry.ajax(), XHR, construct Request() manually. [fail]

Why can the body just disappear?

I don't believe my question is a duplicate of this.


Solution

  • You shouldn't put body inside headers, see example on MDN here.