简体   繁体   English

如何为REST API调用编码URL参数?

[英]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. 我必须创建一些在REST API调用中使用的url参数。 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. 我正在使用Angularjs 1.4.2和一种将参数传递给服务函数的表单,该函数会构建参数并向API进行$ http.post调用。 I created a plunker for the parameter building piece. 我为参数构建块创建了一个插件。

index.html 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 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. 我将硬编码的数据放入名为data的变量中,然后使用$ httpParamSerializerJQLike序列化数据。 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. 使用我的硬编码数据(称为数据),一切正常,并且从我的实际代码中的API调用获得了HTTP 200成功响应。

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. 因此,我为参数创建了一个名为testData的JavaScript对象,使用JSON.stringify将其从对象转换为JSON,然后使用httpParamSerializerJQLike序列化数据。 However, the hardcoded (data) doesn't look like the testData and it's throwing HTTP 401 errors. 但是,硬编码的(数据)看起来不像testData,并且会引发HTTP 401错误。

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 数据为: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 以下是testData的最终结果:testData是:=%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; 解码后的testData显然不适用于URL字符串。

="username":"james@gmail.com","password":"myPassword","grant_type":"password","env":"dev"} =“ 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? 为什么会这样,我必须手动创建一个函数来创建URL字符串,还是有其他解决方案?

We have to give the JavaScript object to the function "httpParamSerializerJQLike()", not string as you are doing JSON.Stringify(testData). 我们必须将JavaScript对象赋予函数“ httpParamSerializerJQLike()”,而不是字符串,因为您正在执行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 您可以使用Object.entries()获取包含JavaScript对象的属性和值的数组的数组,使用Array.prototype.map()迭代该数组,并使用参数""链接.join()来创建查询字符串

 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. 我正在使用Angularjs 1.4.2和一种将参数传递给服务函数的表单,该函数会构建参数并向API进行$http.post调用。

The is no need to manually encode url parameters with the $http service . 无需使用$ http服务手动编码url参数。 Simply use the params property of the config object: 只需使用config对象的params属性:

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

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

See the encoding done with this DEMO on PLNKR . 请参阅在PLNKR上使用此DEMO进行的编码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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