javascript - How to encode URL parameters for REST API call? - Stack Overflow

I have to create a some url parameters that I use in a REST API call. I'm using Angularjs 1.4.2 an

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=".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?

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/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?

Share Improve this question edited Jul 22, 2017 at 4:36 georgeawg 49k13 gold badges77 silver badges98 bronze badges asked Jul 22, 2017 at 1:17 James-Jesse DrinkardJames-Jesse Drinkard 15.7k16 gold badges118 silver badges140 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 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]

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

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744300547a4567479.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信