首页  >  问答  >  正文

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 天前606

全部回复(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
  • 取消回复