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?