angular.module('myApp',[]).config(function($httpProvider) { $httpProvider.defaults.useXDomain = true; delete $httpProvider.defaults.headers .common['X-Requested-With']; $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8'; $httpProvider.defaults.headers.put['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8'; // Override $http service's default transformRequest $httpProvider.defaults.transformRequest = [function(data) { /** * The workhorse; converts an object to x-www-form-urlencoded serialization. * @param {Object} obj * @return {String} */ var param = function(obj) { var query = ''; var 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]; if(subValue != null){ // fullSubName = name + '[' + subName + ']'; fullSubName = name + '.' + subName; // fullSubName = 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; }; return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data; }]; })
感谢,终于找到json数据post到服务器的传输方式,不会再报跨域访问和服务器接收格式的错误
,多个括号的问题烦死我了,({‘{"params1":"xxxx","params2":"cxxxxxx"}‘,‘‘}),终于解决了,
说白了就是转成application/x-www-form-urlencoded , 参数之间加上&
或者你post请求的data,定义由 data: {"params1":"xxxx","params2":"cxxxxxx"} 改成params1="xxxx"¶ms2="xxxx",
1.以下是我定义,主要用于解决跨域访问,是angularjs CORS提供的标准方式
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common[‘X-Requested-With‘];
$httpProvider.defaults.headers.post[‘Content-Type‘] = ‘application/x-www-form-urlencoded;charset=utf-8‘;
$httpProvider.defaults.headers.put[‘Content-Type‘] = ‘application/x-www-form-urlencoded;charset=utf-8‘;
2.
$httpProvider.defaults.transformRequest 这个定义被重写,
帮我们完成了json数据请求转成params1="xxxx"¶ms2="xxxx"格式
时间: 2024-10-23 20:51:02