简体   繁体   English

如何在 Express 中为单个路由禁用 CORS 而无需重写我的所有路由?

[英]How can I disable CORS for a single route in Express without rewriting all of my routes?

TLDR: In the example, I just want to make it so that /users/delete cannot be called by anything outside of my React app. TLDR:在这个例子中,我只是想让/users/delete不能被我的 React 应用程序之外的任何东西调用。

I have a bunch of routes for the backend API of my app that uses Express:我的应用程序使用 Express 的后端 API 有一堆路由:

ie. IE。 server.js服务器.js

app.get('/invoices/read', async (req, res) => {
    // gather data from db
    res.json({...data})
})

I have cors enabled globally like so:我在全球范围内启用了 cors,如下所示:

server.js服务器.js

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

So, my question is, how would I disable CORS for a single route such as this所以,我的问题是,我将如何禁用 CORS 像这样的单一路线

app.post('/users/delete', async (req, res) => {
    // delete user out of database
    res.sendStatus(200)
})

without rewriting all of my routes to something like this:无需将我的所有路线都重写为以下内容:

var cors = require('cors');

app.get('/invoices/read', cors(), async (req, res) => {
    // gather data from db
    res.json({...data})
})

So that a user can't just make a POST request to /users/delete using an arbitrary ID in an attempt to delete a user out of my system?这样用户就不能只使用任意 ID 向/users/delete发出 POST 请求,以试图将用户从我的系统中删除?

Do I need to just include the origin in my headers or do I need to disable CORS for that route?我是否需要在我的标头中包含原点,还是需要为该路由禁用 CORS?

  • In the past, I've had trouble getting a string of origins to work using the Access-Control-Allow-Origin header.过去,我在使用Access-Control-Allow-Origin header 让一系列来源工作时遇到了麻烦。

One other solution I've found:我发现的另一种解决方案:

On the global invocation of app.use(cors()) , you can add the option preflightContinue: true , and that should allow follow-up middleware on the specific page to override it.app.use(cors())的全局调用中,您可以添加选项preflightContinue: true ,这应该允许特定页面上的后续中间件覆盖它。

In the top-level config在顶级配置中

  app.use(
    cors({
      origin: 'http://localhost:9001',
      // Allow follow-up middleware to override this CORS for options
      preflightContinue: true,
    }),
  );

In my specific route declaration在我的具体路线声明中

router.options('/myRoute', cors(myRouteOptions));
router.post(
  '/myRoute',
  cors(myRouteOptions),
  async (req, res) => {
    // ...
  },
);

Override the header only on the route you want to "disable" it:仅在要“禁用”它的路线上覆盖 header:

res.set('Access-Control-Allow-Origin', 'alloweddomain.com')

If you need to allow more than one domain, you can make a list of allowed domains and check if the origin is included there:如果您需要允许多个域,您可以列出允许的域并检查源是否包含在其中:

const allowedDomains = ['allowedomain1.com', 'alloweddomain2.com'];
const origin = req.get('origin');

if (allowedDomains.includes(origin)) {
  res.set('Access-Control-Allow-Origin', origin);
}

Using Express router and cors module:使用 Express 路由器和cors模块:

// Define the router 
const v1 = express.Router();

// Initiate express app
const api = express();

 const corsOptions = {
    origin: '*',
    methods: [],
    allowedHeaders: [],
    exposedHeaders: [],
    credentials: true
};

// Define subroutes here 
v1.get('/list', (req, res) => { // action implementation here})

// Define cors per route 
v1.all('/list', cors(corsOptions));

// Add the router to express  
api.use('/', v1);

Or using a cors middleware或使用 cors 中间件

v1.get('/list',  cors(corsOptions), (req, res) => { // action implementation here})

Both should work, I hope this helps.两者都应该工作,我希望这会有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在Node + Express中,如何为各个路由设置CORS? - In Node+Express, how can I set CORS for individual routes? Express.js路由。 如何在所有现有路线之前放置默认路线 - Express.js routing. How to put a default route before all of my existing routes 如何在Node.js和Express中更好地组织路线? - How can I organize my routes better in nodejs & express? 如何在没有nodejs中所有路由的一个长文件的情况下进行路由? - How can I do my routing without having one long file of all the routes in nodejs? 如何在不重写整个应用程序(Laravel + jQuery,SPA风格)的情况下对结果进行分块(延迟加载?) - How can I chunk results (lazy load?) without rewriting my whole application (Laravel + jQuery, SPA style) 如何在Express 4路由中使用socket.io向连接的套接字发送事件? - How can I emit events to connected sockets using socket.io from within my Express 4 routes? Express.js-用于管理所有路线的单个路线文件 - Express.js - Single routes file that manages all the routes 如何将所有快递页面路由到一个独特的页面(没有 html 扩展名) - How to route all express pages to a unique pages (Without html extension) 如何在不配置路由的情况下检测angularjs单页面应用程序中的页面刷新? - How can I detect a page refresh in an angularjs single page application without configuring routes? 如何在给定的快递文件中分隔路线? - How do I separate routes in my given express file?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM