Understanding the Issue
As a new AngularJS user, you encountered challenges while sending data to the server using the $http service. Specifically, you faced issues when attempting to send data in the URL-encoded format.
The Solution
To resolve this problem, you need to convert your data to URL parameters instead of JSON strings. Ben Nadel explains this in his blog:
By default, the $http service will transform the outgoing request by serializing the data as JSON and then posting it with the content-type, "application/json". When we want to post the value as a FORM post, we need to change the serialization algorithm and post the data with the content-type, "application/x-www-form-urlencoded".
Example
Here's an example that demonstrates how to post URL-encoded form data using $http:
$http({ method: 'POST', url: url, headers: {'Content-Type': 'application/x-www-form-urlencoded'}, transformRequest: function(obj) { var str = []; for(var p in obj) str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p])); return str.join("&"); }, data: {username: $scope.userName, password: $scope.password} }).then(function () {});
Update for AngularJS v1.4 and Later
For AngularJS v1.4 and later, you can leverage the new services available to achieve the same result:
$http({ method: 'POST', url: url, headers: {'Content-Type': 'application/x-www-form-urlencoded'}, transformRequest: $httpParamSerializer });
The above is the detailed content of How to POST URL-Encoded Form Data with AngularJS's $http Service?. For more information, please follow other related articles on the PHP Chinese website!