angularjs post 跨域
生活随笔
收集整理的這篇文章主要介紹了
angularjs post 跨域
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
web api搞好了;用Ajax妥妥的;但是前端用的AngulagJS,也懶得再換為Ajax了;
但是問題來了;提示:
已攔截跨源請求:同源策略禁止讀取位于 http://x.x.x.x:port/api/Person/Update 的遠程資源。(原因:CORS 預檢通道未成功)。
搜索一下:一般就是配置服務器和客戶端的header
找到了一篇可以解決的:http://www.cnblogs.com/BGOnline/p/5996289.html
1.開啟angularjs的CORS支持
.config(function($httpProvider) { // CORS post跨域配置$httpProvider.defaults.useXDomain = true; $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';var param = function(obj) { // 修改angularjs $http.post的默認傳參方式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;};$httpProvider.defaults.transformRequest = [function(data) {return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;}];delete $httpProvider.defaults.headers.common['X-Requested-With']; })
2.開啟服務器端CORS支持
header('Access-Control-Allow-Origin: *');//(我不知道這個是怎么配置的,PHP的?) 我自己的web.config相關配置
<!--跨域..--><httpProtocol><customHeaders><add name="Access-Control-Allow-Origin" value="*" /><!--Content-Type,--><add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" /><add name="Access-Control-Allow-Methods" value="GET,POST,PUT, DELETE, OPTIONS" /></customHeaders></httpProtocol></system.webServer>
?
?
?
?
轉載于:https://www.cnblogs.com/love-zf/p/6265281.html
總結
以上是生活随笔為你收集整理的angularjs post 跨域的全部內容,希望文章能夠幫你解決所遇到的問題。