【问题标题】:No 'Access-Control-Allow-Origin' header is present on the requested resource. Next.js CORS error when using next-connect请求的资源上不存在“Access-Control-Allow-Origin”标头。使用 next-connect 时出现 Next.js CORS 错误
【发布时间】:2021-11-18 10:09:40
【问题描述】:

我正在尝试在 Next.js 中使用 corsnext-connect。但是,我无法使其工作。

这是我的cors 代码:

function handler() {
  if (!COOKIE_SECRET || !SESSION_SECRET)
    throw new Error(
      `Please add COOKIE_SECRET & SESSION_SECRET to your .env.local file!`
    )

  return nc<NextIronRequest, NextApiResponse>({
    onError: (err, _, res) => {
      error(err)
      res.status(500).end(err.toString())
    },
  })
    .use(
      cookieSession({
        name: 'session',
        keys: [COOKIE_SECRET],
        maxAge: 24 * 60 * 60 * 1000 * 30,
        secure: IS_PRODUCTION && !process.env.INSECURE_AUTH,
        signed: IS_PRODUCTION && !process.env.INSECURE_AUTH,
      })
    )
    .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()
    })
}

export default handler

FWIW,我已经尝试过 StackOverflow 上提到的所有其他解决方案,例如 https://stackoverflow.com/a/35317615/6141587

我也尝试过安装 corsnextjs-cors 之类的软件包,但遇到了同样的错误:

从“https://api.twitter.com/oauth/authorize?oauth_token=xxxxxxxxxxxx”(重定向自“http://localhost:3000/api/twitter/generate-auth-link”)获取获取权限来源“http://localhost:3000”已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。

我在这里有一个 Github 副本 → https://github.com/deadcoder0904/twitter-api-v2-3-legged-login-using-next-connect(有关 cors,请参阅 latest commit

我检查了网络的选项卡,但没有看到其中设置标题。我还添加了console.log('cors'),但它没有打印在那里。

我猜中间件 server/api-route.ts 文件根本没有被调用。

我需要该文件作为中间件。我该如何解决?

【问题讨论】:

    标签: node.js express next.js next-connect


    【解决方案1】:

    我实际上并没有调用中间件。它在另一个文件中。

    我删除了cookie-session 并保留了next-iron-session,因为我只需要 1 个会话库。

    然后我将api/twitter/generate-auth-link 路由中的导出作为handler().get(generateAuthLink) 函数的包装器,而不仅仅是generateAuthLink

    然后我将前端更改为不使用fetch,而是使用Link

    这解决了它!

    【讨论】:

      猜你喜欢
      • 2014-07-06
      • 2017-04-11
      • 2022-07-28
      • 2021-04-09
      • 1970-01-01
      • 1970-01-01
      • 2020-02-13
      • 2016-03-20
      • 1970-01-01
      相关资源
      最近更新 更多