2

I'm working on a small ToDo app where I've Angular as front-end and Node.js/Express/Mongo as middleware/backend.

While I submit Login in my Login form, it hits the login API, however it returns one strange output in the console saying

OPTIONS http://localhost:3000/api/v1/users/login/ 0 {}

(see screenshot below) which doesn't allow me to get the dashboard even after successful login.

I've enabled CORS through installing the cors NPM module. and I've checked RESTFul services in Postman, and all are working fine.

[Updated] This is how I've enabled the CORS in my express.js's app.js file.

let cors = require('cors');
app.use(cors());
app.options('*', cors());

Error in console

Rob
  • 14,746
  • 28
  • 47
  • 65
David R
  • 14,711
  • 7
  • 54
  • 72

3 Answers3

2

before a CORS request is sent to the server, clients will always send this "OPTIONS" request as a "preflight request", soliciting supported methods from the server.

This request being blocked may be an indicator of a wrong CORS configuration or an explicit block of all "OPTIONS" requests from the server. (CORS needs to be configured on the server as well).

More information can be found here

Janis Jansen
  • 996
  • 1
  • 16
  • 36
1

It seems that this is a known nodejs issue that is still open.

Based on the open github, seems that the best recommendation is to try something like this:

you need to allow both:

// Http.OPTIONS method for request that is hitting " apiUrl =https://127.0.0.1:3000/login".
// Allow CORS like below:
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'content-type');
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS');

Another great idea is to use the angular proxy settings for local development so that you will not need to add CORS for localhost at all.

Very good guidance in this SO answer here on setting up a proxy for angular If this work, then you can make 100% sure that it is indeed a CORS problem.

Athanasios Kataras
  • 25,191
  • 4
  • 32
  • 61
1

To handle CORS in express you dont need to add any dependency. Notice that http://localhost:4200 is you angular app.

This worked for me:

//Add here whatever route you are using for the api.
app.use('/api', (req, res, next) => {
  //Where http://localhost:4200 is the angular app
  res.header('Access-Control-Allow-Origin', 'http://localhost:4200'),
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
  next();
})

Note: This goes after the place where you import the routes and before where you use them. kind of like:

const apiRouter = require('./app_api/routes/api_routes');
//The code i posted here
app.use('/api', apiRouter);

jogarcia
  • 2,327
  • 2
  • 19
  • 34