0

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);

jQuery POST form data

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) })

Fetch POST

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?

Ari Seyhun
  • 11,506
  • 16
  • 62
  • 109

1 Answers1

1

what you need is to use FormData instead of JSON representation

here is how to do it, basically it looks like this:

var formData = new FormData();
formData.append("username", document.getElementById('username').value);
formData.append("password", document.getElementById('password').value);
pwolaq
  • 6,343
  • 19
  • 45
  • The OP's `requestBody` isn't JSON. JSON is a *textual notation* for data exchange. [(More here.)](http://stackoverflow.com/a/2904181/157247) If you're dealing with JavaScript source code, and not dealing with a *string*, you're not dealing with JSON. – T.J. Crowder Jan 19 '18 at 08:21
  • I did indeed try this actually, but I got something like this instea d https://gyazo.com/1bd671205e9e6d7452319640cb8aa897 – Ari Seyhun Jan 19 '18 at 08:21
  • 1
    @T.J.Crowder I was referring to the second example, but it may be misleading :) – pwolaq Jan 19 '18 at 08:22