首頁  >  問答  >  主體

angular.js - angularjs $http.get無法跨域問題

很簡單的段$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_u1582phpcn_u15822713 天前604

全部回覆(3)我來回復

  • 给我你的怀抱

    给我你的怀抱2017-05-15 16:53:47

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

    回覆
    0
  • 高洛峰

    高洛峰2017-05-15 16:53:47

    你可能需要加上一些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();
    });
    

    回覆
    0
  • PHP中文网

    PHP中文网2017-05-15 16:53:47

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

    回覆
    0
  • 取消回覆