NodeJS Passport的CORS问题,authenticate()未显示Postman get请求,但Nextjs查询资源失败

yeotifhr  于 2022-12-18  发布在  Node.js
关注(0)|答案(1)|浏览(112)

我正在尝试使用Nextjs前端和Expressjs后端进行Google登录。I followed this tutorial.
我使用URL http://localhost:5200/auth/google,并期望得到与使用Postman相同的响应:<title>Sign in - Google Accounts</title>(加上1885行其他内容)
我得到这个错误时,试图通过Nextjs连接:Access to XMLHttpRequest at 'https://accounts.google.com/o/oauth2/v2/auth?response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fauth%2Fgoogle%2Fcallback&scope=email%20profile&client_id=493322088126-0kd18q0if7ccc333b3jahdh5gmgojsbgig.apps.googleusercontent.com' (redirected from 'http://localhost:5200/auth/google') from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
我的前台查询:const response = await axios.get("http://localhost:5200/auth/google");
我的后端中间件:

middlewares: [
        allowAll,
        cors({ origin: "*", methods: "GET, POST, PATCH, DELETE, PUT", allowedHeaders: "Content-Type, Authorization" }),
        accessControlAllowOriginDev,
        bodyParser.json(),
        bodyParser.urlencoded({ extended: true }),
        cookieParser(),
        passport.initialize(),
        (req: any, res: any, next: any) => {
            console.log(req.originalUrl); //confirms the url is correct
            next();
        },
    ]

唯一失败的路由:this.router.get("/google", passport.authenticate("google", { scope: ["email", "profile"] })); // the route is correct
我试过:

  1. Changing the order of the middlewarecors()在堆栈中是最后一个,现在是第一个。
    1.添加passport.initialize()passport.session()。在此之前,这两个都丢失了。但是,非常确定这是无关的。
    1.从Nextjs和Postman发送请求到我的auth控制器的健康检查路由。两者都确认控制器处于活动状态并正在运行。两者都没有被CORS阻止。
  2. This solution,这涉及修改local.settings.json
{
    "Host": {
        "CORS": "*"
    }
}

总之:Postman从端点接收到正确的响应,而Nextjs却没有,Nextjs可以像Postman一样访问healthCheck端点;因此问题是Nextjs和Passport的组合。我不知道出了什么问题。
edit:有人能告诉我吗?如果我正确配置了CORS,* 每个 * 请求都将返回“Allow-access-control-origin:* ”在头上,对吗?我的Postman响应头确实写着X-Powered-By: Express Access-Control-Allow-Origin: *
编辑2:I'm hot on the trail of a solution. This looks similar

biswetbf

biswetbf1#

找到解决方案
[Passportjs][Angular5] No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access
由用户“超级用户Sudo”执行以下操作:
““”
您可以简单地在html模板中编写
<a href="http://localhost:3000/login/google">Google</a>
在后端你只需要有这个
app.get('/login/google', passport.authenticate('google', { scope: ['profile','email']}) );
““”

相关问题