尝试使用 next-connect 从 http://localhost:3000 重定向到 Next.js 中的 https://api.twitter.com 时出现 CORS 错误?

CORS error when trying to redirect from http://localhost:3000 to https://api.twitter.com in Next.js using next-connect?

我正在尝试让 redirect 工作,但总是被控制台中的错误轰炸:

Access to fetch at 'https://api.twitter.com/oauth/authenticate?oauth_token=' (redirected from 'http://localhost:3000/api/auth/twitter/generate-auth-link') from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

我确实看到了关于同一问题的其他答案,事实上,我刚刚发现我恰好在 2 个月前问过 ,但该问题适用于打开弹出窗口 window &那里的重定向&这个想要在同一页面本身上进行重定向。

我也试过同样的答案,但它不起作用,它仍然给我这个代码的 cors 错误:

.use((req, res, next) => {
    console.log('cors')
    res.setHeader('Access-Control-Allow-Origin', '*')
    res.setHeader(
        'Access-Control-Allow-Headers',
        'Origin, X-Requested-With, Content-Type, Accept, Authorization'
    )
    if (req.method == 'OPTIONS') {
        res.setHeader('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE, GET')
        return res.status(200).json({})
    }
    next()
})

我也试过使用这个代码:

const allowedOrigins = ['http://localhost:3000']

const options: cors.CorsOptions = {
    allowedHeaders: [],
    origin: allowedOrigins,
}

.use(cors(options))

但这也不管用。

我的 oauth 流程是这样的:

Click login on http://localhost:3000 → Go to https://api.twitter.com/oauth/authenticate?oauth_token=xxxx → Redirect back to http://localhost:3000

同一 oauth 流程的代码如下所示:

api/auth/twitter/generate-auth-link.ts

import { NextApiResponse } from 'next'
import TwitterApi from 'twitter-api-v2'

import handler from '@/server/api-route'
import { SERVER_URL, TWITTER_CONFIG } from '@/utils/index'
import { NextIronRequest } from '@/types/index'

const generateAuthLink = async (req: NextIronRequest, res: NextApiResponse) => {
    // Generate an authentication URL
    const { url, oauth_token, oauth_token_secret } = await new TwitterApi({
        appKey: TWITTER_CONFIG.consumerKey,
        appSecret: TWITTER_CONFIG.consumerSecret,
    }).generateAuthLink(`${SERVER_URL}/api/auth/twitter/get-verifier-token`)

    req.session.twitter = {
        oauth_token,
        oauth_token_secret,
    }

    await req.session.save()

    // redirect to the authentication URL
    res.redirect(url)
}

export default handler().get(generateAuthLink)

api/auth/twitter/get-verifier-token.ts

import { NextApiResponse } from 'next'
import TwitterApi from 'twitter-api-v2'

import handler from '@/server/api-route'
import { SERVER_URL, TWITTER_CONFIG } from '@/utils/index'
import { NextIronRequest } from '@/types/index'

const getVerifierToken = async (req: NextIronRequest, res: NextApiResponse) => {
    // check query params and session data
    const { oauth_token, oauth_verifier } = req.query

    if (typeof oauth_token !== 'string' || typeof oauth_verifier !== 'string') {
        res.status(401).send('Oops, it looks like you refused to log in..')
        return
    }

    if (!req.session.twitter)
        throw new Error("Can't find `oauth_token` & `oauth_token_secret` in `req.session.twitter`")

    const oauth_token_secret = req.session.twitter.oauth_token_secret

    if (typeof oauth_token_secret !== 'string') {
        res.status(401).send('Oops, it looks like your session has expired.. Try again!')
        return
    }

    // fetch the token / secret / account infos (from the temporary one)
    const { client, accessToken, accessSecret } = await new TwitterApi({
        appKey: TWITTER_CONFIG.consumerKey,
        appSecret: TWITTER_CONFIG.consumerSecret,
        accessToken: oauth_token,
        accessSecret: oauth_token_secret,
    }).login(oauth_verifier)

    const { name, screen_name, email } = await client.currentUser()

    req.session.twitter = { oauth_token: accessToken, oauth_token_secret: accessSecret }
    req.session.user = { name, screen_name, email }
    await req.session.save()

    res.redirect('/app')
}

export default handler().get(getVerifierToken)

如何解决 cors 问题以便重定向正常工作?

当我使用 next-auth 时,它可以工作,但无法从它的代码中找出它发生的位置。但我想要完全相同的流程。单击 Login & 它被重定向到 Twitter API & 当它通过身份验证时,被重定向回 localhost.

,Twitter API 不支持 CORS。

所以我不能只在 api/auth/twitter/generate-auth-link.ts 中执行 res.redirect(url) 所以我使用 res.send({ url }) 发送回 url & 在前端我做了以下操作:

import ky from 'ky'

const res: { url: string } = await ky.get('/api/auth/twitter/generate-auth-link').json()
window.location.href = res.url

成功了!