如何删除这些关于 HEAD 和 OPTIONS 的招摇警告?

How to remove these swagger warnings, about HEAD and OPTIONS?

我在 express js 上使用了 swagger,当我进行查询时,我收到了这个警告。

WARNING! Unable to find a Swagger operation that matches HEAD ... - 这将显示我是否会尝试使用 curl。

WARNING! Unable to find a Swagger operation that matches OPTIONS ... - 而这个是从网页访问的。

我已经将 helmet 和这个添加到代码中。

app.use((_, res: Response, next: NextFunction) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header(
    'Access-Control-Allow-Headers',
    'Origin, X-Requested-With, Content-Type, Accept'
  );
  res.header(
    'Access-Control-Allow-Headers',
    'Content-Type, api_key, Authorization',
  );
  next();
});

我想念什么?

终于成功了,我的意思是警告不再显示了。解决方案只是一行,发送 200 的 HTTP 状态告诉浏览器支持该请求。

export function optionCORS(req: Request, res: Response, next: NextFunction): void {

  // I am just setting the headers if the request is an OPTION or HEAD
  // For now I didn't interfere with the other request like POST, etc.
  // I have a guess that swagger is is doing it.
  if (req.method === 'OPTIONS' || req.method === 'HEAD') {
    const origin: string = req.headers.origin as string;

    // On my angular I have interceptor that will set the ```withCredentials```
    // option to true, so I cant use * on Allow-Origin so I grab the
    // request.headers.origin an used it.
    // Also we need to set the Allow-Credentials to true.
    res.header('Access-Control-Allow-Origin', origin);
    res.header('Access-Control-Allow-Credentials', 'true');

    // Then the usual headers.
    res.header('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE, OPTIONS');    
    res.header(
      'Access-Control-Allow-Headers',
      'Accept, Authorization, Content-Type, Content-Length, Origin, ' +
      'X-Requested-With',
    );

    // And this what I miss, just the HTTP 200 status.
    // So the client will know that the request is supported.
    res.sendStatus(200);
    return;
  }

  // If the request is not an OPTIONS or HEAD continue as usual,
  // it look like swagger is handling it.
  next();
}

那你就可以把它当作中间件使用了。

app.use(optionCORS);

如果您使用 swagger-express-middleware 设置 WARN=off 环境变量

https://github.com/APIDevTools/swagger-express-middleware/blob/ed73f82e57adb868b10e1989dac555b8d943dab8/lib/helpers/util.js#L27