-1

I'm new to node and need some help.

I'm getting: Access to XMLHttpRequest at 'http://localhost:3000/api/auth/signin' from origin 'http://localhost:4200' has been blocked by CORS policy:

my angular app is launching from http://localhost:4200

And I'm making an api request (which works on postman) to http://localhost:3000/api/auth/signin

but I'm getting CORS errors.

In my node server.js, I have the following configured:

    app.use(function (req, res, next) {
      res.setHeader("Access-Control-Allow-Origin", "*");
      res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
      res.setHeader('Access-Control-Allow-Methods', "GET, POST, PATCH, DELETE, OPTIONS");
      next();
    });

And I can post data using postman to: localhost:3000/api/auth/signin

NeNaD
  • 18,172
  • 8
  • 47
  • 89
J.G.Sable
  • 1,258
  • 4
  • 26
  • 62

1 Answers1

-1

It's because Browser will send something called preflight request, and Postman will not. So, your server has to respond to these preflight requests first, in order for Browser to proceed with original request.

Your code will just call next() which will proceed to the next middleware, but what will that middleware do after? You should send 200 on OPTIONS request immediately.


Alternatively, you can quickly add cors logic with cors package:

const cors = require('cors');

...

app.use(cors());
NeNaD
  • 18,172
  • 8
  • 47
  • 89