如何在C++的Drogon框架中实现重定向?
Drogon框架实现页面重定向的方法
Drogon完全支持页面跳转(重定向)功能,主要通过HttpResponse类提供的静态方法实现,操作方式如下:
基础临时重定向(302状态码)
在控制器的请求处理函数中,返回HttpResponse::newRedirectionResponse创建的响应对象即可,支持内部路由或外部网站地址:void YourController::handleRedirect(const HttpRequestPtr &req, std::function<void (const HttpResponsePtr &)> &&callback) { // 跳转到内部路由 auto resp = HttpResponse::newRedirectionResponse("/user/profile"); // 跳转到外部第三方网站 // auto resp = HttpResponse::newRedirectionResponse("https://example.com"); callback(resp); }永久重定向(301状态码)
如果需要告知浏览器该跳转是永久性的,使用HttpResponse::newPermanentRedirectionResponse方法:void YourController::handlePermanentRedirect(const HttpRequestPtr &req, std::function<void (const HttpResponsePtr &)> &&callback) { auto resp = HttpResponse::newPermanentRedirectionResponse("/new-permanent-path"); callback(resp); }
以上两种方式都会让浏览器自动跳转到指定的URL地址,和Flask的redirect(URL)作用完全一致。
内容的提问来源于stack exchange,提问作者Nukchix
相关产品推荐
相关产品推荐

