i've created a small API using Node/Express and trying to pull data using Angularjs but as my html page is running under apache on localhost:8888 and node API is listen on port 3000, i am getting the No 'Access-Control-Allow-Origin'. I tried using node-http-proxy and Vhosts Apache but not having much succes, please see full error and code below.
"XMLHttpRequest cannot load localhost:3000. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'localhost:8888' is therefore not allowed access."
// Api Using Node/Express
var express = require('express');
var app = express();
var contractors = [
{
"id": "1",
"name": "Joe Blogg",
"Weeks": 3,
"Photo": "1.png"
}
];
app.use(express.bodyParser());
app.get('/', function(req, res) {
res.json(contractors);
});
app.listen(process.env.PORT || 3000);
console.log('Server is running on Port 3000')
// Angular code
angular.module('contractorsApp', [])
.controller('ContractorsCtrl', function($scope, $http,$routeParams) {
$http.get('localhost:3000').success(function(data) {
$scope.contractors = data;
})
// HTML
<body ng-app="contractorsApp">
<div ng-controller="ContractorsCtrl">
<ul>
<li ng-repeat="person in contractors">{{person.name}}</li>
</ul>
</div>
</body>
The answer code allow only to localhost:8888. This code can't be deployed to the production, or different server and port name.
To get it working for all sources, use this instead:
Another way, is simply add the headers to your route:
This worked for me.
You can change * to fit your needs. Hope this can help.
You can use "$http.jsonp"
OR
Below is the work around for chrome for local testing
You need to open your chrome with following command. (Press window+R)
Note : Your chrome must not be open. When you run this command chrome will open automatically.
If you are entering this command in command prompt then select your chrome installation directory then use this command.
Below script code for open chrome in MAC with "--allow-file-access-from-files"
second options
You can just use open(1) to add the flags: open -a 'Google Chrome' --args --allow-file-access-from-files