I'm currently trying to write an AJAX call using Angular's $http object in order to send a post request with JSON in the body and a query string appended to the URL. Despite going through the documentation for $http, looking for solutions on SO, and trying different setups, I am still confused about passing the parameters correctly. Currently, my API either returns empty JSON or a Bad Request (400) error.
Code Snippet
function inviteStaff (json) {
authToken = service.getAuthToken();
return $http({
method: 'POST',
url: baseUrl + '/invitations' + '?authToken=' + authToken,
data: JSON.stringify(json),
headers: {
'Content-type': 'application/json'
}
});
}
Function Implementation
self.invite = function ($form) {
self.showLoader = true;
InvitesService.inviteStaff($scope.inviteModel).then(function () {
$form.$setPristine();
$scope.inviteModel.timestamp = new Date();
$scope.invites.unshift($scope.inviteModel);
$scope.inviteModel = self.createNewInvite();
self.showLoader = false;
},
function () {
self.showLoader = false;
});
};
Request Log
data: "authToken=********&t=*****" // strange addition of another parameter here
headers: Object
Accept: "application/json"
Accept-Language: "en"
Content-type: "application/json"
authToken: "*********" // token only
__proto__: Object
method: "POST"
params: Object
timeout: Object
transformRequest: Array[1]
transformResponse: Array[1]
url: "http://****.****.com:****/doctors/invitations?authToken=*****"
__proto__: Object
JSON Parameter Object
{
accountType: "LEAD_DOCTOR",
firstName: "kraken",
lastName: "lastName",
email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5e352c3f353b301e333f3732703d3133">[email protected]</a>"
}
I could use some clarification on how this should be done. Should I pass the json object to data or params? Is JSON.stringify necessary for the data field? I've also seen cases where people passed an empty string to data.
I've been using Charles Proxy as well. While I've made progress, the JSON is appearing as a query string instead of under the JSON filter.
Any suggestions would be appreciated. I plan to transition to using the $resource tool, but due to time constraints, I just need to get this working at the moment. Let me know if more information is needed.
UPDATE We're utilizing Swagger to document our API, and you can actually test the endpoint in their UI. It generates the following CURL command. This might help identify the issue.
curl -X POST --header "Content-Type: application/json" --header "Accept: application/json" -d "{
\"firstName\": \"string\",
\"lastName\": \"string\",
\"email\": \"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="adcfc1ccc5edc0ccc4c183cec2c0">[email protected]</a>\",
\"accountType\": \"CLIENT\"
}" "http://*****.****.com:****/doctors/invitations?authToken=***obfuscatedAuthToken***"