0

Trying to access Node server (http://localhost:3000) from Angular 7 (http://192.168.X.X)

Set CORS i.e.

this.app.use(cors())
this.app.options('*', cors())
this.app.use(bodyParser.json())
this.app.use(bodyParser.urlencoded({ extended: false }))

but getting

Access to XMLHttpRequest at 'http://localhost:3000/' from origin 'http://192.168.X.X:XX' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Tried this middleware function

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

but all in vain. Any help or suggestion that could resolve my issue???

**************** Answer ****************

I was actually making a mistake by using cors() two times as

this.app.use(cors())
this.app.options('*', cors())

so when I used one of them, it worked fine :)

WasiF
  • 26,101
  • 16
  • 120
  • 128

1 Answers1

1

Try adding these two

app.options("/*", function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
    res.sendStatus(200);
});

app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    next();
});
Pankaj Jindal
  • 175
  • 1
  • 2
  • 10