如何在同一上下文中重定向到 url

How to redirect to url within same context

我有 /logout 操作,应该重定向到 /login/login 呈现模板,我在其中从上下文中读取闪现消息。这有效,但浏览器中的 url 仍然是 "/logout":

router.get("/logout").handler((ctx) => {
  if (ctx.user()!=null) {
    ctx.clearUser()
    //flash message
    ctx.put("msg", "Logout succeed")
  }
  ctx.reroute("/login")
})

我想要的,但是url应该是"/login":

更好用(?):

ctx.response.putHeader("location", "/login").setStatusCode(302).end()

但语境不同。所以我还没有闪信。

如何在同一上下文中重定向到 /login

更新 与此相关的问题issue

为了使用 flash 消息,您应该在重定向中添加一个 cookie,内容如下:

// this makes the message available to the client
ctx
  .addCookie(Cookie.cookie("flashMessage", "Logout succeed"));
// configure where to redirect
ctx.response()
  .putHeader("location", "/login");
// perform the redirect
ctx.end(302);

然后在客户端你需要一点 JavaScript 来阅读消息和 随心所欲地进行显示。如果您使用 jQuery 和 cookie 插件,则没有简单的方法可以在浏览器上读取 cookie,您可以执行以下操作:

$.fn.flashMessage = function (options) {
    var target = this;
    options = $.extend({}, options, { timeout: 3000 });
    if (!options.message) {
        options.message = getFlashMessageFromCookie();
        deleteFlashMessageCookie();
    }
    if (options.message) {
        if (typeof options.message === "string") {
            target.html("<span>" + options.message + "</span>");
        } else {
            target.empty().append(options.message);
        }
    }

    if (target.children().length === 0) return;

    target.fadeIn().one("click", function () {
        $(this).fadeOut();
    });

    if (options.timeout > 0) {
        setTimeout(function () { target.fadeOut(); }, options.timeout);
    }

    return this;

    function getFlashMessageFromCookie() {
        return $.cookie("FlashMessage");
    }

    function deleteFlashMessageCookie() {
        $.cookie("FlashMessage", null, { path: '/' });
    }
};

并在 HTML 中添加一个占位符,例如:

<div id="flash-message"></div>

并像这样触发它:

$(function() {
  $("#flash-message").flashMessage();
});