AngularJS CORS Example

An example of an AngularJS App making AJAX requests to a domain that has CORS headers enabled.

by Joe Cisneros

HTML

<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.16/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.16/angular-resource.min.js"></script>
<div ng-controller="myCtrl">
    <fieldset>
        <legend>CORS Example using httpbin.org echo</legend>
        <label for="foo">foo:</label>
        <input type="text" ng-model="foo" />
        <br />
        <button ng-click="getData()">GET Request</button>
        <button ng-click="postData()">POST Request</button>
    </fieldset>
    <br />
    
    <label for="echo">Echo'd Response</label>
    <textarea name="echo" ng-model="response" disabled="disabled"></textarea>
    <label for="full">Full Response</label>
    <textarea name="full" ng-model="fullResponse" disabled="disabled"></textarea>
</div>

CSS

textarea {
    height:50px;
    width:100%;
}

JavaScript

angular.module('myApp', ['ngResource'])
.controller('myCtrl', function ($scope, $http) {
    $scope.foo = "bar";
    $scope.response = [];
    $scope.fullResponse = [];
    
    $scope.getData = function() {
        var data = $.param({
            json: JSON.stringify({
                foo: $scope.foo
            })
        });
        
        // GETs are simple, 
        $http({
          url: "//httpbin.org/get", 
          method: "GET", 
          data: [],
          params: {foo: $scope.foo}
        }).success(function(data, status) {
            $scope.response = "GET Response: " + JSON.stringify(data.args);
            $scope.fullResponse = JSON.stringify(data);
        }); 
    };
    
    $scope.postData = function() {
        
        // Set the Content-Type 
        $http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
        
        // Delete the Requested With Header
        delete $http.defaults.headers.common['X-Requested-With'];

        var data = $.param({
            json: JSON.stringify({
                foo: $scope.foo
            })
        });
        
        $http({
          url: "//httpbin.org/post", 
          method: "POST", 
          data: data
        }).success(function(data, status) {
            $scope.response = "POST Response: " + data.form.json;
            $scope.fullResponse = JSON.stringify(data);
        });
       
    };
});