简体   繁体   中英

How to encode URL parameters for REST API call?

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="angular.js@1.4.2" 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":"james@gmail.com","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":"james@gmail.com","password":"myPassword","grant_type":"password","env":"dev"}

    $scope.data = $httpParamSerializerJQLike({
      "username":"james@gmail.com",
      "password":"myPassword",
      "grant_type":"password",
      "env": "dev"
    });


    function loadTestData(testData){
      testData.username = "james@gmail.com";
      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&username=james@gmail.com

Here is what the testData ends up like: testData is: =%7B%22username%22:%22james@gmail.com%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":"james@gmail.com","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?

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&username=james@gmail.com
The data is: env=dev&grant_type=password&password=myPassword&username=james@gmail.com

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": "james@gmail.com", "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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM