1

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)

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
Anuteja
  • 53
  • 7
  • There are almost 100 questions that ask essentially the same thing: http://stackoverflow.com/search?q=angular+express+Access-Control-Allow-Origin. Did none of these help? – Claies Oct 10 '15 at 17:27
  • Possible duplicate of [How to allow CORS in Express/Node.js?](http://stackoverflow.com/questions/7067966/how-to-allow-cors-in-express-node-js) – Claies Oct 10 '15 at 17:29

1 Answers1

1

Use npm cors - https://github.com/expressjs/cors to allow cors request.

var express = require('express')
  , cors = require('cors')
  , app = express();

app.use(cors());

app.get('/', function(req, res) {
res.json({ message: 'hooray! welcome to our api!' });
});

app.listen(3000);
Bartosz Czerwonka
  • 1,631
  • 1
  • 10
  • 11
  • when I tried to user the code you mentioned, I am getting the following error. POST http://localhost:3000/signup 409 (Conflict) – Anuteja Oct 10 '15 at 22:31
  • Could you show more your code ? Becuase this above code is working and I think you have some problem with other code. – Bartosz Czerwonka Oct 11 '15 at 09:24