Heim  >  Fragen und Antworten  >  Hauptteil

Zugriff auf https://accounts.google.com/o/oauth2/v2/auth abrufen, der von CORS blockiert wurde

Ich sende einen Abruf von React an Express, um mich bei Google zu authentifizieren, aber mein Zugriff ist durch einen CORS-Fehler blockiert. Ich leite POST-Anfragen von React zur Authentifizierung an eine Google-URL um. Ich habe versucht, cors in einer Express-Anwendung zu verwenden, habe aber immer noch den gleichen Fehler erhalten. für das Erhalten von

const handleClick = (e) => {
    fetch('http://localhost:8000/api/mail/login', {
        method: 'POST'
    })
    .then(res => res.text())
}

Cors in Express app.js verwenden

app.use(cors())

Versuchen Sie, zur Google-Authentifizierung umzuleiten

const oauth2Client = new google.auth.OAuth2(
    process.env.CLIENT_ID,
    process.env.CLIENT_SECRET,
    process.env.REDIRECT_URI
)

const url = oauth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: process.env.SCOPE
})

const gmail = google.gmail({
    version: 'v1',
    auth: oauth2Client
})

router.post('/login', (req, res, next) => {
    res.redirect(url)
})

Fehler: Zugriff auf „https://accounts.google .com/o/oauth2/v2/auth?access_type=offline&scope=https%3A%2F%2Fmail.google.com%2F&response_type=code&client_id=727520060136“ zur Extraktion – ngpfd4ll798v42gfclh7cms9ndqstt32. apps.googleusercontent.com&redirect_uri=http%3A%2F%2Flocalhost%3A8000' (umgeleitet von 'http://localhost:8000/api/mail/login') vom Ursprung 'http://localhost:3000' war CORS-Richtlinie Blockierung: Der Header „Access-Control-Allow-Origin“ ist auf der angeforderten Ressource nicht vorhanden. Wenn eine undurchsichtige Antwort Ihren Anforderungen entspricht, legen Sie den Anforderungsmodus auf „no-cors“ fest, um die Ressource mit deaktiviertem CORS zu erhalten.

P粉398117857P粉398117857321 Tage vor719

Antworte allen(1)Ich werde antworten

  • P粉201448898

    P粉2014488982023-11-04 09:56:59

    身份验证流程必须发生在可见的浏览上下文中,不使用 fetch 请求。换句话说:您必须导航当前选项卡到(或打开一个新选项卡)http://localhost:8000/api/mail/login,该选项卡将被重定向到 https://accounts.google.com/o/oauth2/v2/auth?..。并且该页面变得可见。现在,用户必须与该页面交互以选择/确认他们的 Google 帐户,之后他们将被重定向到您服务器上的页面,并在 URL 中包含授权代码(例如,http://localhost:8000/callback?code =...)并且您的服务器必须通过服务器到服务器调用交换访问令牌的授权代码。

    这样发出的请求都不是跨源的,因此根本不会涉及 CORS。

    您需要一个类似的登录表单,而不是 handleClick 函数

    <form action="http://localhost:8000/api/mail/login" method="post">
      <input type="submit" value="Press to log in"/>
    </form>
    

    Antwort
    0
  • StornierenAntwort