$http No 'Access-Control-Allow-Origin' problem on POST

I have not been able to get Angular $http to communicate with a remote REST service. I have tried Restangular and $resource too. The problem seems to be with the underlying $http service.

I am getting the following error:

XMLHttpRequest cannot load http://www.EXAMPLE-DOMAIN.com/api/v2/users/sign_in. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access. 

I have researched this a lot. Currently I have tried setting the $httpProvider headings when configuring my app module and played with $http headers. Below is some of my current code.

My Service

app.service('Auth', function($http) {

			var headers = {
				'Access-Control-Allow-Origin' : '*',
				'Access-Control-Allow-Methods' : 'POST, GET, OPTIONS, PUT',
				'Content-Type': 'application/json',
				'Accept': 'application/json'
			};

			return $http({
				method: "POST",
				headers: headers,
	      url: 'http://www.EXAMPLE-DOMAINcom/api/v2/users/sign_in',
				data: {"email":"my@email.com","password":"secret"}
	    }).success(function(result) {
					console.log("Auth.signin.success!")
					console.log(result);
	    }).error(function(data, status, headers, config) {
					console.log("Auth.signin.error!")
	        console.log(data);
	        console.log(status);
	        console.log(headers);
	        console.log(config);
	    });

});

App Config

var app = angular.module('starter', ['ionic', 'app.controllers', $httpProvider])

.config(['$httpProvider', function($httpProvider) {
        $httpProvider.defaults.useXDomain = true;
        $httpProvider.defaults.headers.common = 'Content-Type: application/json';
        delete $httpProvider.defaults.headers.common['X-Requested-With'];
    }
])

I didn’t have any luck with the settings you have in your App Config. The headers you are setting will have no affect. The headers have to be returned in the response from the server. Sometimes, running a local http server helps with this issue. I didn’t have any issues running on a device or simulator(within Cordova mobile app). I only had some issues running in a desktop browser. In my case, I have control over the server and can enable CORS functionality on it. If you dont have that luxury, I have read some cases where a proxy service can be used to get around this issue. I hope that helps in some way.

On the server-side I did the following. Its a java based RestEasy backend. So I added a filter in web.xml that does this:

String acrHeaders = request.getHeader(“Access-Control-Request-Headers”);
String acrMethod = request.getHeader(“Access-Control-Request-Method”);

response.setHeader(“Access-Control-Allow-Origin”, “*”);
response.setHeader(“Access-Control-Allow-Headers”, acrHeaders);
response.setHeader(“Access-Control-Allow-Methods”, acrMethod);

Thanks Keith,

I will likely be making a server update eventually. However I discovered two things that helped me solve this for my development environment.

  1. The PhoneGap build for the app does not have the CORS issue. So no problem on actual builds…
  • I can turn off CORS security on my Chrome browser for testing. I only run this no-CORS browser when in dev. You can do this on OSX with the following command: open -a Google\ Chrome --args --disable-web-security I just created a little bin script for it.

Thanks for the help!

1 Like

Hello everybody.

I solved ‘Access-Control-Allow-Origin’ problem by adding CORS filter on server side. Let me know if anybody is facing this issue. I will post my code and steps.

Hey guys,

I actually wrote a full step by step tutorial on how to do this, and you can view it here: Posting data from Ionic app to PHP server. I also created a Github project for it, so you can clone it and check out code there.

Hope this will help anyone who stumbles onto this question in the future.

Just so I give you the “main” point, which is as other guys basically said (but a bit more detailed), is the Access-Control-Allow-Origin. This is my “API”, in PHP:

<?php
//http://stackoverflow.com/questions/18382740/cors-not-working-php
if (isset($_SERVER['HTTP_ORIGIN'])) {
    header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Max-Age: 86400');    // cache for 1 day
}

// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS");         

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
        header("Access-Control-Allow-Headers:        {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

    exit(0);
}


//http://stackoverflow.com/questions/15485354/angular-http-post-to-php-and-undefined
$postdata = file_get_contents("php://input");
if (isset($postdata)) {
	$request = json_decode($postdata);
	$username = $request->username;

	if ($username != "") {
		echo "Server returns: " . $username;
	}
	else {
		echo "Empty username parameter!";
	}
}
else {
	echo "Not called properly with username parameter!";
}
?>
5 Likes

can you guild me how to config that ? i have angular and WCF service, i can get but post…please :((

If you’re testing locally use this chrome extension i’ve been using it a while now you can also try running the app on a device and check out the debugger in chrome

1 Like

An easy fix is to download the CORS plugin for your browser. Then just whitelist your API URL so any further requests you make will not be blocked because of the cross-origin issues.

Hi rajil
I would really appreciate if you can post your code and steps, I am having the same problem.
Thanks a lot!

Using CORS plugin on browser just help only you, others will still get the “Access Control Allow Origin” problem. you should understand what is Access-Control-Allow-Origin and how it works first.

Checkout the tutorial here How Access Control Allow Origin works

XMLHttpRequest cannot load http://lvh.me:3000/user_types. No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://lvh.me:9000’ is therefore not allowed access. The response had HTTP status code 404.

<<< \

Hi @keithdmoore I am getting above error in windows

A 404 would indicate either the url is wrong or the resource cannot be found.

this solution for post
what about get data from server ?

Hi,
I have the same problem as following

XMLHttpRequest cannot load http://myLink. No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://localhost:8100’ is therefore not allowed access. The response had HTTP status code 401.

But i need to change only in client side i cant change in server side. can u give me any steps to do this???

Hi guys, i struggled for way too long with CORS issues caused by the interaction of an emulated Ionic project (running localy) with some small Node.JS webservices (also running localy).

Behold the short easy workaround : Chrome’s plugin AllowControlAllowOrigin.

Just switch the radio button from red to green, and no more blocked request, error or warning !
Of course it’s a temporary solution and you may have to put your hands in your request headers when the time to stop the local tests will come. In the meantime, that’s a great way to avoid loosing time on those anoying recurrent issues.

Hi I want your help for No ‘Access-Control-Allow-Origin’ header is present on the requested resource

please post your code, i am going crazy over this issue… tried a lot but still not working

(Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

Thanks clembl,
that solution worked for me.

Easy fix:

  1. Create chrome shortcut
  2. Add flags “–user-data-dir=“C:/ChromeDevSession” --disable-web-security” at the end of Object string.
    e.g.
    “C:\Program Files (x86)\Google\Chrome\Application\chrome.exe” --user-data-dir=“C:/ChromeDevSession” --disable-web-security

Don’t forget to call it ‘DEV’ or something similar to use it ONLY for development your local app.