简体   繁体   English

如何使用 FastAPI 在 HTMX 前端使用 HX-Redirect?

[英]How to use HX-Redirect in HTMX frontend using FastAPI?

I'm trying to redirect on the frontend after a login.我试图在登录后在前端重定向。 I make a request from my htmx frontend like this我像这样从我的 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>

My authenticate endpoint looks like this我的身份验证端点如下所示

@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})

I know the code works because auth_success.html is successfully swapped on the frontend but what I expect to happen next is for the browser to redirect to the homepage( http://127.0.0.1:8000/ ), but it doesn't happen.我知道代码有效,因为auth_success.html在前端成功交换,但我希望接下来发生的是浏览器重定向到主页( http://127.0.0.1:8000/ ),但它没有发生.

My CORS settings are all correct我的CORS设置全部正确

        allow_origins=origins,
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
        expose_headers=["*"],

NOTE: Using RedirectResponse wouldn't work because of how HTMX(not HTML) works.注意:由于 HTMX(非 HTML)的工作方式,使用RedirectResponse无效。 It'll only call the endpoint and swap it's response into <div id="success"></div> which is not a redirect.它只会调用端点并将其响应交换到<div id="success"></div>这不是重定向。

The reason for the redirection not taking place is due to the way you attempt adding the HX-Redirect header to the response.重定向未发生的原因是您尝试将HX-Redirect header 添加到响应的方式。 You are currently adding it to the Response object;您当前正在将其添加到Response object; however, since you are returning a TemplateResponse instead, the header is not added to the response you are actually returning.但是,由于您返回的是TemplateResponse ,因此不会将 header 添加到您实际返回的响应中。 Hence, you should instead add the HX-Redirect header to the TemplateResponse , similar to the example below:因此,您应该改为将HX-Redirect header 添加到TemplateResponse ,类似于以下示例:

@router.post('/authenticate', response_class=HTMLResponse)
async def authenticate(request: Request, email: str = Form(), password: str = Form()):
    # ...
    
    data = {'msg': 'Logged in successfully'}
    response = templates.TemplateResponse('auth_success.html', {'request': request, 'data': data})
    response.headers['HX-Redirect'] = 'http://127.0.0.1:8000/'
    return response

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM