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:
- To use runkit as a server [fail]
- To use express on localhost as a server [fail]
- 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.
- Check all the headers and CORS policy [doesn't help]
- 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. :)
Not a duplicate of this.
CodePudding user response:
You shouldn't put body
inside headers
,
see example on MDN here.