AngularJS: POST Data to External REST API AngularJS: POST Data to External REST API angularjs angularjs

AngularJS: POST Data to External REST API


Your two problems are actually one problem. The OPTIONS request is part of the CORS process. For POST requests, the browser first sends an OPTIONS call, and the server responds if it is okay to execute it.

If the OPTIONS request fails, Angular / Chrome shows you the reason in the console. For example:

OPTIONS https://*** Request header field Content-Type is not allowed by Access-Control-Allow-Headers. angular.min.js:106XMLHttpRequest cannot load https://***. Request header field Content-Type is not allowed by Access-Control-Allow-Headers. 

You probably have to set Access-Control-Allow Headers on the server, too:

header('Access-Control-Allow-Headers: Content-Type, x-xsrf-token')

x-xrsf-token is for angular' to prevent CSRF. You may have to add more headers, depending on what you send from the client.

Here is a very good guide on CORS: https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS


In AngularJS to make CORS working you also have to overwrite default settings of the angular httpProvider:

var myApp = angular.module('myApp', [    'myAppApiService']);myApp.config(['$httpProvider', function($httpProvider) {        $httpProvider.defaults.useXDomain = true;        delete $httpProvider.defaults.headers.common['X-Requested-With'];    }]);

Just setting useXDomain to true is not enough. AJAX request are also send with the X-Requested-With header, which indicate them as being AJAX. Removing the header is necessary, so the server is not rejecting the incoming request.

Note: Answer only works for older AngularJS version previous to 1.2. With 1.2 and above you don't have to do do anything to enable CORS.


Better to solve this problem at the server. On apache you can solve it like this in a .htaccess file. This is a source of pain for angular development and can be solved in angular as well but its probably not the best way to do it.

Header set Access-Control-Allow-Origin "*"Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"