While looking at tutorials and code examples from different places, I noticed that sometimes in a code the JSON object sent through the "data" header in a HTTP request is processed with JSON.stringify(data) before being sent, and sometimes they send it without being "stringified" first.
Using examples from .NET WEB API tutorials, client-side code:
var data = {
Email: self.registerEmail(),
Password: self.registerPassword(),
ConfirmPassword: self.registerPassword2()
};
$.ajax({
type: 'POST',
url: '/api/Account/Register',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(data)
}).done(function (data) {
self.result("Done!");
}).fail(showError);
In this example, if I understand correctly this will convert data into something like:
{"Email":"alice@example.com","Password":"Password1!","ConfirmPassword":"Password1!"}
But in this part from the same client-side code:
var loginData = {
grant_type: 'password',
username: self.loginEmail(),
password: self.loginPassword()
};
$.ajax({
type: 'POST',
url: '/Token',
data: loginData
}).done(function (data) {
self.user(data.userName);
// Cache the access token in session storage.
sessionStorage.setItem(tokenKey, data.access_token);
}).fail(showError);
JSON.stringify() isn't used. What would be the difference? If I'm understanding correctly, HTTP requests are text-based and therefore I used to stringify all my requests.
EDIT:
These are the data-bound elements with KnockoutJS:
//...Other HTML markups...
<input class="form-control" type="text" data-bind="value: registerEmail"/>
//...Other HTML markups...
<input class="form-control" type="password" data-bind="value: registerPassword"/>
//...Other HTML markups...
<input class="form-control" type="password" data-bind="value: registerPassword2" />
//...Other HTML markups...
<input class="form-control" type="text" data-bind="value: loginEmail"/>
//...Other HTML markups...
<input class="form-control" type="password" data-bind="value: loginPassword"/>