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>

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM