You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Express中禁用OPTIONS请求?扫描发现相关低危漏洞

Should You Disable the HTTP OPTIONS Method & How to Do It in Express?

Great question—let’s break this down clearly, no jargon overload.

First: Do You Need to Disable OPTIONS?

It all boils down to your app’s needs:

  • Don’t disable if you use CORS: The OPTIONS method is non-negotiable for cross-origin resource sharing (CORS) preflight requests. If your frontend lives on a different domain than your Express backend, browsers send OPTIONS requests first to check if cross-origin actions (like PUT/DELETE with custom headers) are allowed. Killing OPTIONS here will break your cross-origin functionality entirely.
  • Consider restricting/disabling if no CORS is needed: If your app is strictly same-origin or never needs to handle external cross-origin requests, limiting OPTIONS can reduce minor information disclosure (since it returns your server’s supported method list). That said, this is a low-risk issue—most attackers won’t gain meaningful leverage from this info, but it’s a quick hardening step if you don’t need the method.

How to Handle OPTIONS in Express

Option 1: Restrict OPTIONS to Return Only Your Used Methods

Instead of disabling entirely, just trim the Allow header to the methods your app actually uses. This keeps OPTIONS functional if needed while avoiding oversharing:

app.use((req, res, next) => {
  if (req.method === 'OPTIONS') {
    // Swap these with the methods your app actually supports
    res.setHeader('Allow', 'GET, POST, PUT, DELETE');
    return res.sendStatus(200);
  }
  next();
});

Option 2: Fully Disable OPTIONS Requests

If you’re 100% sure you don’t need OPTIONS at all, you can reject all such requests outright:

// Block OPTIONS for every route
app.options('*', (req, res) => {
  res.sendStatus(405); // Sends "Method Not Allowed"
  // Or use 403 Forbidden if you want to explicitly mark it as blocked
  // res.sendStatus(403);
});

Heads Up if Using the cors Middleware

If you’re using Express’s official cors package, it automatically handles OPTIONS preflight requests. To customize its behavior, tweak the methods or optionsSuccessStatus properties when setting up the middleware:

const cors = require('cors');

app.use(cors({
  // Limit allowed methods for preflight checks
  methods: ['GET', 'POST', 'PUT', 'DELETE'],
  optionsSuccessStatus: 200
}));

内容的提问来源于stack exchange,提问作者Carson Yau

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 09:03:29