I'm attempting to make a POST request to a URL on my website in JavaScript.
I previously was using jQuery's $.post()
function which sends the data object correctly as is, but when attempting to switch to the built-in Fetch()
method, I am struggling to send the data in the same form as the jQuery method.
I have the following JavaScript object:
let requestBody = {
username: document.getElementById('username').value,
password: document.getElementById('password').value,
}
and I'm attempting to make a POST
request to the URL '/user/login'
.
The following jQuery method works:
$.post('/user/login', requestBody);
But when trying with the Fetch
method:
fetch(new Request('/user/login'), { method: 'POST', body: requestBody })
I do not see any form body in the Chrome developer tools.
If I try to stringify the requestBody
object:
fetch(new Request('/user/login'), { method: 'POST', body: JSON.stringify(requestBody) })
You can see I do not have any data under Form Data
as I do with jQuery, and instead it is under Request Payload
. The problem with this, is that it is incompatable with my already written backend code.
How can I POST a JavaScript object to a URL with Fetch()
just as a jQuery $.post()
would?