0

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...!!!";
            }
        })
5

3 Answers 3

3

You can't solve it through javascript. The server you are making the request to has to implement CORS to grant JavaScript from your website access. Your JavaScript can't grant itself permission to access another website.

Sign up to request clarification or add additional context in comments.

Comments

3

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) {
       // ...
     })

5 Comments

I have tried Jsonp but it is not working for me can you please provide me example ?
@Hkachhia Example provided.
@Thanks: Is it use same syntax for post data ?
@Hkachhia As I said, you can't use jsonp to send POST requests, or any kind of requests other than GET.
Oh sorry. But how to POST data in cross domain ? you know that then help me
1

You have to enable CORS on your response. A workaround is to use the enable CORS plugin for Chrome However, be aware that this is not a solution for real customers and it will have side effects on your browser. Only use it for testing.

The real fix is something that you have to do on the server side. The way of enabling Allow-Control-Allow-Origin on your backend depends on the architecture of your backend. Add 'Allow-Control-Allow-Origin' to the header of your response and the problem will be fixed.

For PHP add the following to your response header

header("Access-Control-Allow-Origin: *");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.