-1

I am new to node.js and trying to make Rest API, now my REST API working fine but whenever i called this services through angularjs, it gives me "access-control-allow-origin" error. However, i added this code on server side :-

var express = require("express");  
var app = express();
var router = express.Router();

app.use(function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET, OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
    res.header('Access-Control-Allow-Credentials', true);
    return next();
});

But its not working for me, i searched a lot but didn't get feasible solution, please help me out.

Error is :- enter image description here

  • 1
    How are you calling the API? are you invoking http OPTIONS method . Also, you have only GET and OPTIONS method allowed here, are you using only these two. – TruckDriver Aug 04 '17 at 07:20
  • did you send a post requst – Sachila Ranawaka Aug 04 '17 at 07:20
  • Can you post the API, in which you are trying to call? – Vishnu T S Aug 04 '17 at 07:25
  • Yes, for testing purpose i used only Get , i also post my angular side coding, please have a look – Mahesh Verma Aug 04 '17 at 07:26
  • Possible duplicate of [AngularJS: No "Access-Control-Allow-Origin" header is present on the requested resource](https://stackoverflow.com/questions/29547003/angularjs-no-access-control-allow-origin-header-is-present-on-the-requested-r) – Hitmands Aug 04 '17 at 07:35
  • It looks like your last edit removed a section of code, Mahesh. Would it not be best to leave that in? Additionally, your edit has overwritten mine, which reduced chatty material and repair case errors. Whenever you see an in-editor warning, it is best to back out, refresh and make changes again, so as not to undo a volunteer's work. – halfer Aug 04 '17 at 07:51

2 Answers2

1

You are using http module of angular, if yes, then Angular sends a pre-flight options before actual request. Your server should return 20X for OPTIONS for angular to make actual request.

You can avoid this by handling OPTIONS separately ,

app.use(function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET, OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
    res.header('Access-Control-Allow-Credentials', true);


  if (req.method == "OPTIONS") {
          response.statusCode = 200 //although correct code should be 204,
      return;
        }

    return next();
});

Also a more exhaustive and less restrictive CORS filter will look like below, use it as per your need

            resp.header("Access-Control-Allow-Origin", "*");
            resp.header("Access-Control-Allow-Credentials", "true");
            resp.header("Access-Control-Allow-Methods", "POST, GET, PUT,PATCH, OPTIONS, DELETE");
            resp.header("Access-Control-Max-Age", "3600");
            resp.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, Authorization, Origin, Accept, Access-Control-Request-Method, Access-Control-Request-Headers");

            resp.header("Access-Control-Expose-Headers", "Authorization");
TruckDriver
  • 1,383
  • 13
  • 28
  • where i used this code :- if (req.method == "OPTIONS") { response.statusCode = 200 //although correct code should be 204, return; } – Mahesh Verma Aug 04 '17 at 07:34
  • edited my answer, been some time since i looked into node.js maybe there is a syntax error there,, you can try it. – TruckDriver Aug 04 '17 at 07:36
  • What error are you getting in the browser console? Can you paste it here? – TruckDriver Aug 04 '17 at 07:41
  • XMLHttpRequest cannot load http://localhost:9000/employees. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:50171' is therefore not allowed access. dashboard-services.js:38 Oops and error null //due to my console.log :50171/#/:1 XMLHttpRequest cannot load http://localhost:9000/employees. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:50171' is therefore not allowed access. dashboard-services.js:38 Oops and error null – Mahesh Verma Aug 04 '17 at 07:45
  • In the network tab can you check whether it is failing in get or in options?, you can expand each request and check in request headers, check what error code your server is returning ? – TruckDriver Aug 04 '17 at 07:51
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/151035/discussion-between-timothy-and-mahesh-verma). – TruckDriver Aug 04 '17 at 07:51
0

The browser sends a preflight request before making the actual request. You need to add code for handling this requests, Try this in your server side code.

const cors = require('cors')
const corsOptions = {
  origin: '*'
}
app.use(cors(corsOptions))
Vishnu T S
  • 3,476
  • 2
  • 23
  • 39
  • I already did this, but this was not working for me, then after a long research i saw most of the place set the header part in node.js, then i used this approach. – Mahesh Verma Aug 04 '17 at 07:43
  • I think that you need not to add CORS npm in your project . Just add Google chrome extension, which solve CORS problem. –  Aug 04 '17 at 08:23