angular-tutorial
angular-tutorial copied to clipboard
Angular的post请求后台接受不了数据的解决方法
方案1
加上这个模块,这里改写了**$httpProvider**服务
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;
}];
});
var app = angular.module('wscat', ['MyModule']);
app.controller('loginCtrl', function($scope, $http) {
$scope.name = 'wscat';
$scope.submit = function() {
$http.post('http://localhost/CI/myCi/index.php/login_api/login', {
params: {
username: $scope.username,
password: $scope.password
}
}).success(function(data) {
})
}
})
更改前的数据格式为
更改过后数据格式为下图
我们就可以在后台获取数据了
public
function login() {
$this -> load -> model('login_model');
$data = array(
'user_name' => $this->input->post('params')['username'],
'password' => md5($this->input->post('params')['password'])
);
//or
var_dump($_POST['params']);
}
方案2
原因:可以发现传参方式是request payload
,参数格式是json,而并非用的是form传参,所以在后台用接收form数据的方式接收参数就接收不到了
POST表单请求提交时,使用的Content-Type是application/x-www-form-urlencoded
而此处的Content-Type是:
解决:增添两段代码,代码如下;
$http({
method: 'post',
url: 'http://localhost:8081/search',
data: {
"page": page,
"pageNum": pageNum
},
headers: { //1.设置类型
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
},
transformRequest: function(obj) { //2.处理传递参数的格式
var str = [];
for(var p in obj) {
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]))
}
return str.join('&')
}
}).then(function(data) {
}, function(err) {
});
现在的谷歌监视为:
现在传参方式就变成form方式了,然后后端就可以正常接收参数了!