Performing an AngularJS $http POST request with a combination of JSON parameter and query string

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***"

Answer №1

If you want a suggestion, I would advise utilizing the header field:

function inviteStaff (json) {
authToken = service.getAuthToken();
return $http({
    method: 'POST',
    url: baseUrl + '/invitations',
    data: JSON.stringify(json),
    headers: {
        'Content-type': 'application/json',
        'authToken': authToken
    }
   });
 }

Afterwards, on the server side, request the current value of authToken from the header.

It is worth mentioning that passing tokens in the URL raises some security concerns. You can read more about this here: https URL with token parameter : how secure is it?

Answer №2

After investigating further, we discovered that an HTTP Interceptor function in another part of our codebase was altering the content-type. By implementing a condition around this function, we were able to resolve the issue. A big thank you to all those who provided assistance in verifying the correctness of my code!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Storing session information in a different controller

Currently, I am working on an MVC project that consists of two controllers named ReportsController and ReportViewerController. In the ReportsController, there is a method that I need to call via AJAX: public void Report(ReportWrapper pW) { ...

Bidirectional data binding in AngularJS for <option> elements generated from an AJAX request

I have built a Controller called WebsiteController with the following functionality: JApp.controller('WebsiteController', function($scope, $resource) { var UsersService = $resource('/auth/users', {}); $scope.adding = false; ...

Having trouble releasing the package on npm platform

I'm facing difficulties in publishing a public package to npm. Despite creating an organization, I'm unable to figure out how to add a new package. Any assistance on this matter would be greatly appreciated. https://i.sstatic.net/RMKU9.png ...

Unable to figure out a method to properly synchronize a vue.js asynchronous function

I am facing an issue with my code where everything works fine if I uncomment the "return" statement in fetchData. How can I make sure that I wait for the completion of this.fetchData before populating the items array? I have tried using promises, async/awa ...

Organize a collection of objects into a fresh array

I am facing an issue where I have an array and I need to transform it into an array of its children elements. var data = [{ name: 'Cars', content: 'BMW', value: 2000 }, ...

Loop through the JSON data and dynamically display corresponding HTML code based on the data

I've developed a survey application using React, where I initially wrote code for each question to display radio buttons/inputs for answers. However, as the survey grew with multiple questions, this approach resulted in lengthy and repetitive code. To ...

Guide: "Sending an AJAX request upon selecting an item in a Vue.js 'Select' element using vue-resource"

Is it possible to send an ajax request through vue-resource when a specific item is selected from a "Select" in vuejs? Check out the demo here: https://jsfiddle.net/xoyhdaxy/ <div class="container" id="app"> <select v-model="selected"> ...

Enhancing caching through JSPM optimization

I have successfully configured my workflow to utilize JSPM, resulting in the creation of a production bundle consisting of two large injected and hashed files called main-{hash}.min.css and main-{hash}.min.js. My inquiry pertains to the efficiency of sepa ...

Using soapUI to extract information from a JSON Response with arrays

After receiving a JSON response from a previous test step in soapUI, I am working on parsing the information using a groovy script. Here's a snippet of the JSON response: { "AccountClosed": false, "AccountId": 86270, "AccountNumber": "2915", ...

Storing Scrapy results in separate JSON entities using a while loop

Using a while-loop to scrape various fields on a webpage, I aim to store the output for each loop iteration in separate json objects. While this process functions flawlessly on my local machine with Scrapy 0.24.6 and Python 2.7.5, it encounters issues on ...

Including content without triggering the digest cycle (utilizing raw HTML) within a Directive

My goal is to include raw HTML inside a directive for later transclusion (to populate a modal when opened). The issue arises when the contents of dialog-body are executed, triggering the ng-repeat loop and causing the template to be rerun, leading to a po ...

Vue alert - Cannot access indexOf property of a value that is undefined

After browsing through numerous similar issues on StackOverflow, none seem to address the specific problem I encountered... I have been smoothly working on a Vue JS project + Laravel until I suddenly encountered an error that seems unsolvable (even though ...

Tips on organizing orders by various cities with Laravel, MySQL, and JSON

I am currently working on generating a report with order-related information from a Laravel project. However, I am facing challenges in determining the specific data structure required for this task. Here is what I need: // Date Ranges $fromDate = $this- ...

When implementing variables from input boxes, my SQL query fails to populate any data in the database table

I have been using phpMyAdmin to store test data. As I try to insert data from a form, I encounter an issue where no data gets inserted when using variables in the SQL query. Being new to coding, I am struggling to find a solution to this problem. Additiona ...

Is there a way to conceal a div element if the user is not logged in?

I have been enlisted to assist my friend with a project involving his website. Within the site, there is a checkbox that prompts the display of a div when selected. I believe it would be more effective for this checkbox to only be visible to users who are ...

Exploring the Jquery functionality: $(document).ready(callback);

Hey there, I'm struggling to run a function both on window resize and document ready. The issue is that when the resize event is triggered by mobile scroll, it's essential to ensure the height hasn't changed. Oddly enough, the code works fin ...

retrieving JSON data from the request body

I have been struggling to send a JSON String from an AJAX call to a Jersey web service. Despite researching various related questions and articles, I have not been successful in getting it to work. When monitoring my calls through Fiddler, I can see the ...

Error: Swagger-codegen encountered an issue where 'Object' arguments were disregarded

I've encountered a strange error that I can't seem to troubleshoot through online searches. My current project involves converting swagger files to typescript using a script. The error message simply states what's in the title, and unfortuna ...

Prevent removal of item from ngRepeat

Seeking a method to capture the removal of an element within an ngRepeat loop. My goal is to incorporate animations during this process. While handling the addition of elements can be done using the 'link' event, I am uncertain how to intervene d ...

Using jQuery to smoothly add a new item to the beginning of a group of items

Calling myself a semi-newbie when it comes to jQuery; still struggling with this... I have a bunch of items listed on a page, and my goal is to add a new item at the top of the list by (a) moving the existing items down and (b) smoothly fading in the new ...