Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect to url within same context

Tags:

vert.x

I have /logout action, that should redirect to /login. /login renders template, where I read flash message from context. This works, but url in browser is still remains "/logout":

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

What I want, but url should be "/login":

enter image description here

Better to use(?):

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

But there is different context. So I haven't flash message.

How to redirect to /login within same context?

Upd. Question related to this issue

like image 716
zella Avatar asked Dec 31 '25 10:12

zella


1 Answers

In order to work with flash messages you should add a cookie to the redirect with the content:

// 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);

Then on the client side you need a bit of JavaScript to read the message and perform the display as you wish. Since there is no simple way to read cookies on the browser if you're using jQuery with the cookie plugin you can do something like:

$.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: '/' });
    }
};

And add a placeholder in your HTML like:

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

And trigger it like:

$(function() {
  $("#flash-message").flashMessage();
});
like image 84
Paulo Lopes Avatar answered Jan 03 '26 10:01

Paulo Lopes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!