Here is the skeleton to call the fetch()
function in JavaScript:
javascriptlet response = await fetch(url, { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({name: 'Elon', year: 1971}) });
Per the documentation:
Both requests and responses may contain body data. A body is an instance of any of the following types:
As you can see, you can't use an object in the body field, that's the reason why you should use JSON.stringify()
instead of an object like in the headers field.
If you don't want to stringify your object, you could aso use the following request:
javascriptlet response = await fetch(url, { method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: 'name=Elon&year=1971' });
Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.