I am trying to build an application with angularjs as front end and rest api using express js. I built both the projects using yeoman and my angular app is running on localhost:9000 and my express app is running on localhost:3000. When i try to talk to express js app from angular, I am getting a cross domain request, is there any way to fix this.
app.js in Express App
var routes = require('./routes/signup')(app); //This is the extra line
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "{GRUNT_SERVER}");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
res.header("Access-Control-Allow-Credentials", "true");
next();
});
app.get('/', function(req, res) {
res.json({ message: 'hooray! welcome to our api!' });
});
app.js in angularjs app
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
$httpProvider.defaults.withCredentials = true;
Error
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:9000' is therefore not allowed access.
The response had HTTP status code 409.
EDIT
Here's the code that I added to my app.js file:
// allow CORS:
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8000');
next();
});
This also throws the same error ("No 'Access-Control-Allow-Origin' header is present on the requested resource.") as before.
EDIT
After using
var express = require('express')
, cors = require('cors')
, app = express();
app.use(cors());
This is throwing POST localhost:3000/signup 409 (Conflict)