使用angularJS跨域请求 [英] Cross domain request using angularJS

查看:141
本文介绍了使用angularJS跨域请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想显示使用API​​ angularJS数据。这code工作运行同一台PC上code时的罚款。但是,当我试图测试另一台电脑,然后它会显示错误上没有的访问控制允许来源标头的请求的资源present。 angularjs

我使用1.4.8

下面是我的code:

  $ HTTP({
            方法:获取,
            网址:'HTTP://IP/Test_API/index.php/test123_api/empdtl_from_empid/emp_id/'+$scope.empId
        })
        .success(功能(响应){
            如果(响应!= NULL ||响应!='不确定'){
                $ scope.empNm = response.data.emp_name;
            }
        })
        .error(功能(响应){
            如果(response.status code == 404)
            {
                $ scope.errorEmpNm =您可能输入错误的员工标识已不存在,请输入正确的员工标识...... !!!;
            }
        })


解决方案

您可以尝试 $ http.jsonp(),它可以使跨域请求,但只有请求方法的选择是获取,你不能用它来携带大量负载,因为浏览器可能会限制URL的长度。

示例

注意在 回调= JSON_CALLBACK 在URL!

  VAR URL =htt​​p://other.domain.com/some/path?callback=JSON_CALLBACK;
$ http.jsonp(URL,{params:一个{参数1:值1,参数2:值2}})
     .success(功能(响应){
       // ...
     })
     .error(功能(响应){
       // ...
     })

I would like to display data from API using angularJS. This code works fine when run code on same PC. But when I tried to test on another PC then it is displaying error no access-control-allow-origin' header is present on the requested resource. angularjs

I am using 1.4.8

Here is my code :

$http({
            method:"get",
            url: 'http://IP/Test_API/index.php/test123_api/empdtl_from_empid/emp_id/'+$scope.empId
        })
        .success( function( response ){
            if (response != null || response != 'undefined') {
                $scope.empNm = response.data.emp_name;
            }
        })
        .error( function( response ) {
            if(response.statusCode == 404)
            {
                $scope.errorEmpNm = "You May Inputted Wrong Employee Id which have not Exist, Please Enter Correct Employee Id...!!!";
            }
        })

解决方案

You can try $http.jsonp(), it can make cross-origin requests, but the only option of request method is GET, and you can't use it to carry large payload because the browser may restrict URL length.

Example

Pay attention to the callback=JSON_CALLBACK in the url!

var url = "http://other.domain.com/some/path?callback=JSON_CALLBACK";
$http.jsonp(url, {params: {param1: value1, param2: value2}})
     .success(function(response) {
       // ...
     })
     .error(function(response) {
       // ...
     })

这篇关于使用angularJS跨域请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆