我试图在登录后在前端重定向。我像这样从我的 htmx 前端发出请求
<form hx-post="/authenticate" hx-target= "#success" id="login-form">
<div id="success" class="mb-2"></div>
</div>
.......input fields and submit button.....
</form>
我的身份验证端点如下所示
@router.post("/authenticate", response_class=HTMLResponse)
async def authenticate(request: Request, response: Response, email: str = Form(), password: str = Form()):
..........
#auth logic#
............
response.headers["HX-Redirect"] = "http://127.0.0.1:8000/"
data = {
"success": "Logged in successfully"
}
return web_config.templates.TemplateResponse("auth_success.html", {"request": request, "data": data})
我知道代码有效,因为auth_success.html
在前端成功交换,但我期望接下来发生的是浏览器重定向到主页(http://127.0.0.1:8000/ http://127.0.0.1:8000/),但它没有发生。
我的 CORS 设置都是正确的
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
expose_headers=["*"],
注意:使用RedirectResponse
由于 HTMX(而不是 HTML)的工作方式,无法工作。它只会调用端点并将其响应交换为<div id="success"></div>
这不是重定向。