Monday, 15 February 2021

Can I extend the cors to the routers from app?

I have two questions:

  • Can I use cors() once in my server.js instead of calling and use it in all my router files?
  • Can I require express once in my server.js instead of calling it in all my router files?

My server.js now has no problems to handle CORS like below but the app also handles the users router.

server.js handles requests to /

const cors = require('cors');
const express = require('express');
const users = require('./routers/users');
const app = express();
app.use(cors());
app.use('/api/v1/user', users); // Register the user router

routers/users.js handles requests to /users

const cors = require('cors'); // Required again
const express = require('express'); // Required again
const router = express.Router();
router.use(cors());

If I don't use router.use(cors()) I will receive an CORS on the browser when I access /api/v1/users



from Can I extend the cors to the routers from app?

No comments:

Post a Comment