0

I have to create a some url parameters that I use in a REST API call. I'm using Angularjs 1.4.2 and a form to pass the parameters to a service function, which builds the parameters and makes the $http.post call to the API. I created a plunker for the parameter building piece.

index.html

<!DOCTYPE html>
<html>

  <head>
    <script data-require="[email protected]" data-semver="1.4.2" src="https://code.angularjs.org/1.4.2/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body ng-app="app">
    <div ng-controller="mainCtrl">
      testData is: {{testData}}<p></p>
      The data is: {{data}}
    </div>
  </body>

</html>

script.js

// Code goes here
var app = angular.module("app", []);

app.controller('mainCtrl', function($scope, $httpParamSerializerJQLike) {
    //Create JavaScript object.
   var testData = {};

    //Load the object with the same data as data.
    testData = loadTestData(testData);
    console.log("testData is: " + JSON.stringify(testData));
    //testData is: {"username":"[email protected]","password":"myPassword","grant_type":"password","env":"dev"}

    //Use stringify to make it into a JSON string.
    $scope.testData = $httpParamSerializerJQLike(JSON.stringify(testData));
    //Decoded testData
    //={"username":"[email protected]","password":"myPassword","grant_type":"password","env":"dev"}

    $scope.data = $httpParamSerializerJQLike({
      "username":"[email protected]",
      "password":"myPassword",
      "grant_type":"password",
      "env": "dev"
    });


    function loadTestData(testData){
      testData.username = "[email protected]";
      testData.password = "myPassword";
      testData.grant_type = "password";
      testData.env = "dev";
      return testData; 
    }
});

I put hardcoded data into a variable called data, then use $httpParamSerializerJQLike to serialize data. With my hardcoded data, called data, everything works fine and I get the HTTP 200 success response from the API call in my actual code.

So I created a JavaScript object called testData for the parameters, turned it from an object to JSON using JSON.stringify, then used httpParamSerializerJQLike to serialize the data. However, the hardcoded (data) doesn't look like the testData and it's throwing HTTP 401 errors.

I created a plunker to try and see what is happening. In the plunker, here is what the hardcoded (data) ends up like:

The data is: env=dev&grant_type=password&password=myPassword&[email protected]

Here is what the testData ends up like: testData is: =%7B%22username%22:%[email protected]%22,%22password%22:%22myPassword%22,%22grant_type%22:%22password%22,%22env%22:%22dev%22%7D

Decoded testData is obviously not right for a URL string;

="username":"[email protected]","password":"myPassword","grant_type":"password","env":"dev"}

Why is this and do I have to manually create a function to create the URL string or is there another solution?

3 Answers 3

2

We have to give the JavaScript object to the function "httpParamSerializerJQLike()", not string as you are doing JSON.Stringify(testData).

Try this, it worked for me:

    $scope.testData = $httpParamSerializerJQLike(testData);

Now the output is:

testData is: env=dev&grant_type=password&password=myPassword&[email protected]
The data is: env=dev&grant_type=password&password=myPassword&[email protected]
Sign up to request clarification or add additional context in comments.

1 Comment

JSON is a string format. Do you mean JavaScript object?
0

You can use Object.entries() get an array of arrays containing properties and values of a JavaScript object, iterate the array with Array.prototype.map(), chain .join() with parameter "" to create a query string

let o = {
  "username": "[email protected]",
  "password": "myPassword",
  "grant_type": "password",
  "env": "dev"
};

let props = Object.entries(o);
let params = `?${props.map(([key, prop], index) => 
                `${key}=${prop}${index < props.length -1 ? "&" : ""}`
             ).join("")}`;

console.log(params);

7 Comments

I'm using ES5, so let isn't an option, but I upvoted because I liked your code. Thanks!
The code does not do proper percent encoding. For example, [email protected] should be encoded james%40gmail.com.
@georgeawg What do you suggest adjusting? Using encodeURIComponent()? fetch() passes the parameters as query string parameters
@georgeawg encodeURIComponent(params) results in james%40gmail.com, the dot character is not encoded as %40.
%40 is the percent encoding of @. The dot . character is an unreserved character and does not need percent encoding.
|
0

I'm using Angularjs 1.4.2 and a form to pass the parameters to a service function, which builds the parameters and makes the $http.post call to the API.

The is no need to manually encode url parameters with the $http service. Simply use the params property of the config object:

var params = {name: "joe"};
var config = { params: params };

var httpPromise = $http.post(url, data, config);

See the encoding done with this DEMO on PLNKR.

4 Comments

Where do you use encodeURIComponent() at your own Answer?
The percent encoding is handled by the $http service.
The same is not true for fetch()? You did not answer the question at stackoverflow.com/questions/45249692/…
That does not answer the question. fetch() passes the correct query string parameters when params variable at Answer is concatenated to URL.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.