0

I'm having a huge problem with CORS.
I'm developing in AngularJS using NodeJS Express and I have another API running in another IP/PORT (both are in the same machine). I'm coding functions in Angular to consume the API.

When I try to get/post/delete/put I receive this message:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:3000' is therefore not allowed access.

There's a lot of solutions here in Stackoverflow to configure the app.js. One configuration that I've tried and still not working:

app.use(function (req, res, next) { res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type'); res.setHeader('Access-Control-Allow-Credentials', true); next(); }); 

I have installed the npm cors module. I've edited my app.js to enable the cors module and still not working:

var express = require('express'); var cors = require('cors'); app.use(cors()); 

Any solutions? I have no idea how to fix it! Btw I'm using Chrome.

4
  • You're adding those to the API server, right? Commented Apr 9, 2017 at 6:24
  • What do your ajax calls look like? Are they all GET requests? Do they have any custom headers? DELETE and PUT will require support for the OPTIONS command because the browser will preflight those wiht OPTIONS first to see if cross-origin is allowed. Custom headers can also force a pre-flight OPTIONS request. Commented Apr 9, 2017 at 6:34
  • @robertklep Wow! I thought that I needed to config the NodeJS server and not the API! Now it's working fine :D Commented Apr 9, 2017 at 6:44
  • Victor, what do you mean? Commented Nov 6, 2017 at 19:50

3 Answers 3

1

Put this in your http request on angular

$http.post(url, {withCredentials: true, ...}) 

Also you can put this config in app.js for all requests:

$httpProvider.defaults.withCredentials = true; 
Sign up to request clarification or add additional context in comments.

Comments

0

put the following in your app.js file:

app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); next(); }) 

and then use the 'CORS' module in each of the routes:

router.post('/create',cors(), function (req,res) { 

Comments

0

This is what works for me on Node.js v6.4.0 and Express 4.13.4

There was no need for me to use the cors module. Simply:

app.use(function (req, res, next) { res.header("Access-Control-Allow-Origin", "*") res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept") next() }) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.