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 top answer worked fine for me, except that I needed to whitelist more than one domain.
Also, top answer suffers from the fact that
OPTIONS
request isn't handled by middleware and you don't get it automatically.I store whitelisted domains as
allowed_origins
in Express configuration and put the correct domain according toorigin
header sinceAccess-Control-Allow-Origin
doesn't allow specifying more than one domain.Here's what I ended up with:
Try adding the following middleware to your NodeJS/Express app (I have added some comments for your convenience):
Hope that helps!
Install cors dependency in your project:
Add to your server configuration file the following:
It works for me with 2.8.4 cors version.
Accepted answer is fine, in case you prefer something shorter, you may use a plugin called cors available for Express.js
It's simple to use, for this particular case: