angular.js - angularjs $http.get无法跨域问题
phpcn_u1582
phpcn_u1582 2017-05-15 16:51:47
0
3
601

很简单的段$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

reply all(3)
给我你的怀抱

1) Cross-domain has nothing to do with what kind of framework is used,
(PS: After adding API_HOST_URL to another page, the post value goes to that path, and no cross-domain error is reported, but the same is copied and used in get The method does not work) Is the other page the same domain as your page? Is it the same problem when using get/jsonp on another page?
2) After using JSONP, please check whether the returned data content meets the json format requirements. If not, a similar error will be reported
Uncaught SyntaxError: Unexpected token :

小葫芦

You may need to add some headers:

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

If you want to cross-domain, jsonp is preferred, and then ensure that the server returns it in the normal js syntax format
For example, the return value is:
var test = {"status":1,"data":5};

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!