[eggjs/egg]前扶手分离项目中,ctx.redirect跨域问题

2025-11-04 632 views
2
Background

起因是我想在前后端分离项目中实现一个后端鉴权的功能 client: localhost:8000 server: localhost:7000 oauth: https://example.gitlab.com/oauth/authorize

利用egg-passport和egg-passport-oauth2插件来实现鉴权

期望结果:当没有权限时,跳转到https://example.gitlab.com/oauth/authorize 现实结果: 跳转到outh服务时会出现跨域问题,Origin为null.我有按照egg-security设置domain白名单,仍然无效。

我查到是redirect的问题,于是我在controller里使用

ctx.redirect('https://example.gitlab.com/oauth/authorize')直接进行跳转(没设置状态码),发现也会存在这样的跨域问题。

如果我设置了状态码

// controller.js
getTest() {
    this.ctx.unsafeRedirect('http://localhost:8000/spartan_dashboard/miniprogram/template')
   this.ctx.status = 200
 }

此时可以前端来操作跳转,但是与我的想法相悖

请问我这样使用ctx.redirect是否有误?在这种前后端分离的场景应该怎么使用?

回答

0

请提供最小复现repos

2

Hello @Gong-Elory. Please provide a reproducible example following the instruction.

Issues labeled by Need Reproduce will be closed if no activities in 7 days.

@Gong-Elory,请根据这个说明提供最小可复现代码。

如果在 7 天内没有进展会被自动关闭。

1

我也遇到了这个问题,目前也是采用设置状态码由前端来操作跳转的方式进行跳转,目前还未找到好的解决方案,请问你找到解决方案了吗

7

嗨,我们需要更多信息来跟进这个问题,建议npm init egg --type=simple提供一个小型项目并上传到您的 GitHub。

目前由于缺乏活动,此问题将暂时关闭。如有更多信息,请随时重新打开此问题。

0

@arron-lb 需要提供复现方式,你不会是期望通过 ajax 来 redirect 吧?

8

@atian25 @Gong-Elory 要设置 config 白名单和 service this.ctx.redirect(url),控制器 中设置 302 状态

2

@Gong-Elory 请问问题解决了吗? 我也遇到了重定向报跨域的问题