问题
I am using angular.js to make a ReSTful app for mobile devices using cordova. for server side I am using slim framework.all according to this tutorial:(http://www.angularcode.com/user-authentication-using-angularjs-php-mysql/)
But when i uploaded api folder to server, error occurs : No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'localhost' is therefore not allowed access. The response had HTTP status code 404.
I have read about adding "Access-Control-Allow-Origin" and implemented it according to this link : http://help.slimframework.com/discussions/problems/810-no-subject
$app->get('/session', function() {
**$response->header('Access-Control-Allow-Origin', '*');**
$db = new DbHandler();
$session = $db->getSession();
$response["uid"] = $session['uid'];
$response["email"] = $session['email'];
$response["name"] = $session['name'];
echoResponse(200, $session);
});
also tried
$app->get('/session', function() {
**$session->header('Access-Control-Allow-Origin', '*');**
$db = new DbHandler();
$session = $db->getSession();
$response["uid"] = $session['uid'];
$response["email"] = $session['email'];
$response["name"] = $session['name'];
echoResponse(200, $session);
});
I am still receiving the same error.
--> Also is the last line correct ? echoResponse(200, $session);
Thank You in advance :)
update
I am using same file on firefox and chrome and chrome is able to access the file on server. Also one JSON file on my server was being accessed by cordova app earlier and now is not working. The calling code is exactly same ie
.controller('ListController', ['$scope', '$http', function($scope, $http) {
$http.get('js/data.json').success(function(product_data) {
$scope.artists = product_data;
});
}])
回答1:
Open Chrome with the --disable-web-security
flag. This will prevent that from showing up and allow you to develop on your desktop.
Cordova / PhoneGap basically do this for you when it's in app form. You may need to have a look around to see how to open it with the flag depending on which operating system you're on.
Also, do not continue to use your browser for normal activities with the flag enabled. If possible, also use the CLI to open a new user profile so it doesn't affect your existing profile and open you up to any security vulnerabilities.
回答2:
Some web browsers disallow CORS from localhost (or any alias for localhost such as 127.0.0.1). The solution is to access it using non-localhost url.
One such url that may work is your IP address.
If you prefer not to use your IP address (maybe because it's assigned randomly by your router each time you connect) then you can assign a fake domain to yourself by modifying /etc/hosts
(or Windows\System32\Drivers\etc\hosts
on Windows).
For example, add this to /etc/hosts
:
127.0.1.1 thismachine
Then you can access your web server by typing http://thismachine
in your web browser.
来源:https://stackoverflow.com/questions/30142590/no-access-control-allow-origin-header-is-present