Как убрать эти предупреждения о чванстве, о заголовке и опциях? - PullRequest
0 голосов
/ 08 декабря 2018

Я использовал swagger для экспресс-js, и когда я делаю запрос, я получаю это предупреждение.

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();
});

Что мне не хватает?

1 Ответ

0 голосов
/ 09 декабря 2018

Наконец-то все заработало, я имею в виду, что предупреждение больше не отображается.Решение заключается в том, чтобы отправлять HTTP-статус 200, сообщая браузеру, что запрос поддерживается.

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);
...