The problem and solution of $http of AngularJs sending POST request and php unable to receive Post data

  • 2021-08-06 20:17:59
  • OfStack

Recently, in the development of AngularJs+Php, I encountered that php can't receive the data from AngularJs in the background, and there are many solutions on the Internet, but they are all point-to-point. After many explorations, record the solutions:

tips: The currently used AngularJs version is v 1.5. 0-rc. 0

Cause analysis:

It is very simple to make post requests when using jquery.


$.ajax({
 type: 'POST',
 url:'process.php',
 data: formData,
 dataType: 'json',
 success: function(result){
 //do something
 }
 });

We generally use serialize () or serializeArray () to process the transmitted data, but when sending post request, jquery will convert this object into a string and then send it, similar to "a=123 & b=456".
However, AngularJs transmits one Json data instead of one converted string, so it can't be received directly by $_ POST when it is received at php. Thus, data can't be obtained.
The $POST mode can only receive data submitted by Content-Type: application/x-www-form-urlencoded, which is the data submitted by the form.
However, it can be received using file_get_contents ("php://input"), and Post data without Content-Type specified can also be received. At this time, the obtained string needs to be converted again to become the data format we want. This undoubtedly increases the workload.

Solution:

1. Refer to JQuery, serialize the parameters using JQuery's $. param () method and pass


$http({
 method : 'POST',
 url: 'process.php',
 data: $.param($scope.formData), // Serialization parameter 
 headers: { 'Content-Type': 'application/x-www-form-urlencoded' } )
})   

2. Get reprocessing using file_get_contents ("php://input")


$input = file_get_contents("php://input",true);
echo $input;   

3. Modify the default handling of $httpProvider for Angular (Reference: http://victorblog.com/2012/12/20/make-angularjs-service-behave-like-jquery-ajax/)


// Your app's root module...
angular.module('MyModule', [], function($httpProvider) {
 // Use x-www-form-urlencoded Content-Type
 $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
 
 /**
 * The workhorse; converts an object to x-www-form-urlencoded serialization.
 * @param {Object} obj
 * @return {String}
 */
 var param = function(obj) {
 var query = '', name, value, fullSubName, subName, subValue, innerObj, i;
 
 for(name in obj) {
 value = obj[name];
 
 if(value instanceof Array) {
 for(i=0; i<value.length; ++i) {
 subValue = value[i];
 fullSubName = name + '[' + i + ']';
 innerObj = {};
 innerObj[fullSubName] = subValue;
 query += param(innerObj) + '&';
 }
 }
 else if(value instanceof Object) {
 for(subName in value) {
 subValue = value[subName];
 fullSubName = name + '[' + subName + ']';
 innerObj = {};
 innerObj[fullSubName] = subValue;
 query += param(innerObj) + '&';
 }
 }
 else if(value !== undefined && value !== null)
 query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
 }
 
 return query.length ? query.substr(0, query.length - 1) : query;
 };
 
 // Override $http service's default transformRequest
 $httpProvider.defaults.transformRequest = [function(data) {
 return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
 }];
});

$http({
 method:"POST",
 url:"/api/login.php",
 data:$scope.Account
});

Supplement:

php can also be obtained through $GLOBALS['HTTP_RAW_POST_DATA'] Gets the raw data submitted by POST.

But $GLOBALS['HTTP_RAW_POST_DATA'] Whether to save data from POST in centent-Type depends on the setting of centent-POST, that is, POST data must be explicitly indicated Content-Type: application/x-www-form-urlencoded The data of POST will be stored in $GLOBALS['HTTP_RAW_POST_DATA'] Medium.

Summarize


Related articles: