Node.js中如何为部分路由(如user/*)禁用CORS
/user/* API Paths Great question! Right now you’re applying strict CORS rules globally to all routes. To target /user/* paths specifically to "disable" CORS (either allowing any origin access or skipping CORS checks entirely), you can adjust how you apply the CORS middleware—since Express lets you scope middleware to specific routes.
Here are two practical approaches based on what you mean by "disable CORS":
Approach 1: Allow Any Origin for /user/* Paths
If you want to let any origin access /user/* endpoints (while keeping your strict rules for other routes), use this setup:
First, keep your existing corsOptions definition. Then add a permissive CORS config for user paths, and apply middleware in the correct order:
// Your existing strict CORS options var corsOptions = { origin: function (origin, callback) { if (origin.search("^.*"+whitelist+".*$")>-1 || origin.search("^.*"+whitelist2+".*$")>-1) { callback(null, true) } else { callback(new Error('Not allowed by CORS')) } }, optionsSuccessStatus: 200, credentials: true }; // Permissive CORS config for /user/* (allows any origin) var corsPermissiveOptions = { origin: true, // Grants access to any origin optionsSuccessStatus: 200, credentials: true // Keep this if you need to send cookies/auth headers }; // Apply permissive CORS to /user/* first app.use('/user/*', cors(corsPermissiveOptions)); // Apply strict CORS to all other routes app.use(cors(corsOptions));
Note: If you don’t need credentials for /user/* routes, you can use origin: "*" instead of origin: true—but remember, credentials: true can’t be used with * (browsers will block this combination).
Approach 2: Skip CORS Middleware Entirely for /user/*
If you want to avoid sending any CORS headers at all for /user/* (only safe if these endpoints are accessed from the same origin or non-browser clients), apply your strict CORS middleware to all routes except /user/*:
var corsOptions = { origin: function (origin, callback) { if (origin.search("^.*"+whitelist+".*$")>-1 || origin.search("^.*"+whitelist2+".*$")>-1) { callback(null, true) } else { callback(new Error('Not allowed by CORS')) } }, optionsSuccessStatus: 200, credentials: true }; // Apply strict CORS to all routes EXCEPT /user/* app.use(function(req, res, next) { if (!req.path.startsWith('/user/')) { return cors(corsOptions)(req, res, next); } next(); });
Quick Tips:
- Middleware order matters! For Approach 1, make sure the
/user/*middleware runs before the global strict CORS middleware. - If you have specific routes under
/user/(like/user/profileor/user/login), you can apply the permissive CORS directly to those individual routes instead of using a wildcard:app.get('/user/profile', cors(corsPermissiveOptions), (req, res) => { // Your route logic here });
内容的提问来源于stack exchange,提问作者venkat osiz

