Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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]

For Christ sake, please any hits why body can just dissapear, I have a deadline tomorrow. 🙂

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Not a duplicate of this.

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading