@artuh_a

Как решить ошибку CORS: «Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.»?

Прикручиваю авторизацию через гугл аккаунт.

Сервер nodejs на Koa http://localhost:3000, фронт - react http://localhost:8000.

На клиенте создаю запрос:
login: () => {
    const request = new Request('http://localhost:3000/auth/google', {
      credentials: 'include',
      headers: new Headers({
        'Access-Control-Allow-Headers': 'Content-Type',
        'Access-Control-Allow-Credentials': true,
        'Content-Type': 'application/json',
      }),
    });
    return fetch(request)
      .then((response) => {
        if (response.status < 200 || response.status >= 300) {
          throw new Error(response.statusText);
        }
        return response.json();
      })
      .then(({ token }) => {
        localStorage.setItem('token', token);
      });
  }


На сервере его обрабатываю:
authModule.initPassportStrategies(passport);

apiAuthRouter
  .get(
    '/auth/google',
    passport.authenticate('google', {
      scope: ['profile', 'email'],
    }),
  )
  .get('/auth/google/callback', (ctx) => {
    return passport.authenticate('google', (err, user) => {
      if (user) {
        ctx.login(user);
      }

      ctx.redirect('http://localhost:8000');
    })(ctx);
  });


Для авторизации с google использую модуль passport-google-oauth:
function initPassportStrategies() {
  passport.serializeUser((user, done) => {
    done(null, user);
  });
  passport.deserializeUser((user, done) => {
    done(null, user);
  });

  passport.use(
    new GoogleStrategy(
      {
        clientID,
        clientSecret,
        callbackURL: 'http://localhost:4000',
      },
      (token, refreshToken, profile, done) => {
        return done(null, { profile, token });
      },
    ),
  );
}


Сразу после запроса выдается ошибка:
Access to fetch at 'https://accounts.google.com/o/oauth2/v2/auth?...' (redirected from 'http://localhost:4000/auth/google') from origin 'http://localhost:8000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.


Вот сами запросы:
Request URL: http://localhost:4000/auth/google
Request Method: GET
Status Code: 302 Found
Remote Address: [::1]:4000
Referrer Policy: no-referrer-when-downgrade
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: http://localhost:8000
Connection: keep-alive
Content-Length: 5
Content-Type: text/plain; charset=utf-8
Date: Tue, 19 May 2020 09:22:29 GMT
Location: https://accounts.google.com/o/oauth2/v2/auth?...
Vary: Origin
accept: application/json
Accept-Encoding: gzip, deflate, br
Accept-Language: en-GB,en-US;q=0.9,en;q=0.8,ru;q=0.7
access-control-allow-credentials: true
access-control-allow-headers: Content-Type
access-control-allow-methods: GET
access-control-allow-origin: http://localhost:8000
Cache-Control: no-cache
Connection: keep-alive
content-type: application/x-www-form-urlencoded
Host: localhost:4000
Origin: http://localhost:8000
Pragma: no-cache
Referer: http://localhost:8000/
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
User-Agent: ...


Request URL: https://accounts.google.com/o/oauth2/v2/auth?...
Provisional headers are shown
Referer: http://localhost:8000/
User-Agent: ...
response_type: code
redirect_uri: http://localhost:4000/auth/google/callback
scope: profile email
client_id: ...


Если с клиента напрямую переходить по ссылке localhost:3000/auth/google экран с авторизацией гугл открывается.

Из статьи пробовал указывать в запросе заголовки:
Access-Control-Allow-Origin: http://localhost:8000
Access-Control-Allow-Methods: GET
Access-Control-Allow-Headers: Content-Type

- результата это не дало.

Может ли кто-то подсказать как правильно настроить CORS в моем случае либо хотя бы натолкнуть в правильную сторону, что можно еще попробовать сделать?
  • Вопрос задан
  • 5443 просмотра
Пригласить эксперта
Ответы на вопрос 2
@loonny
Ваш localhost доступен только вам. Ошибку просто переведите

CORS: «Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.»

CORS: «Ответ на предварительный запрос не проходит проверку контроля доступа: перенаправление не разрешено для предварительного запроса.»
Ответ написан
Попробуйте добавить в код выделенное жирным

const request = new Request('http://localhost:3000/auth/google', {
      credentials: 'include',
     <b> mode: 'cors' </b>  <i>// no-cors, *cors, same-origin</i>
      headers: new Headers({
        ....
      }),
    });
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы