angular.js - angularjs $http.get無法跨域問題
phpcn_u1582
phpcn_u1582 2017-05-15 16:51:47
0
3
597

很簡單的段$http.get向介面請求資料的方法。但是就是不知道什麼原因,一直提示無法跨域。請問該怎麼解決? (PS:在另一個頁面加入API_HOST_URL後,post值到那個路徑,沒有報過任何無法跨域的報錯,但是同樣的複製過來,在get方法下卻不管用)

function togetpNo($scope,$http){
    var array=$scope.array;
    $http.get(API_HOST_URL+'/ss/test.do?pNo='+array)
     .success(function(data){
 alert(data);
 }).error(function(e){
 alert('请求失败了');
 })
}

報錯內容:
XMLHttpRequest cannot load http://datatest.dev:8081/ss/test.do?pNo=h01,h02. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost :8080' is therefore not allowed access.

改成用jsonp寫:

 $http.jsonp(API_HOST_URL+"/ss/test.do?jsonp=JSON_CALLBACK&pNo="+array)

報錯誤:Uncaught SyntaxError: Unexpected token :

phpcn_u1582
phpcn_u1582

全部回覆(3)
给我你的怀抱

1)跨域和使用什麼樣的框架無關,
(PS:在另外一個頁面加入API_HOST_URL後,post值到那個路徑,沒有報過任何無法跨域的報錯,但是同樣的複製過來,在get方法下卻不管用) 另外一個頁面和你頁面同域否? 另外一個頁面中使用get/jsonp也是同樣的問題嗎?
2)使用JSONP後,請檢查傳回的資料內容是否符合json格式要求,如果不符合,就會報類似錯誤
Uncaught SyntaxError: Unexpected token :

小葫芦

你可能需要加上一些header:

app.all('*', function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By", ' 3.2.1');
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});
Ty80

要跨域首選jsonp,然後就是保證伺服器端以正常的js語法格式回傳
例如回傳值為:
var test = {"status":1,"data":5};

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!