Setting cookies in mojolicious response
Asked Answered
C

1

9

How do i set a cookie in mojolicious response and later read it from the request. I tried different ways but none of them set cookie on the response object.

tried these ways

$self->res->cookies({name => 'foo', value => 'bar'});
$self->res->headers->set_cookie('foo=bar');
$self->res->headers->cookie('foo=bar');

plz, help!!

thanks.

Corcoran answered 7/3, 2012 at 21:6 Comment(0)
W
16

You can use the shortcut methods directly from the controller:

# Set
$self->cookie(foo => 'bar');

# Get
$self->cookie('foo');

http://mojolicio.us/perldoc/Mojolicious/Controller#cookie

However, if your intent is simply to store a value and retrieve it on subsequent requests, there's no need to set cookies directly. Mojolicious sessions use signed cookies by default, will handle the complexities of the cookies, and will verify that the values have not been changed by the client.

# Set
$self->session(foo => 'bar');

# Get
$self->session('foo');

http://mojolicio.us/perldoc/Mojolicious/Controller#session

If sessions are the best solution for you, make sure you set your app secret. Also, check out: http://mojocasts.com/e4#Session

Whereof answered 7/3, 2012 at 21:28 Comment(4)
Thanks for the quick response..I tried the session, it works that way..but is there another way where I can explicitly set a cookie on the response and retrieve it on subsequent request.Corcoran
Yes - the first part of the answer.Whereof
Thanks..but none of them worked until i set path =/. I did $self->res->headers->set_cookie('foo=bar; Path=/'); and retrieved it like $self->cookie('foo');Corcoran
That is strange. What version of Mojolicious are you using? Regardless, you still don't have to set it directly. See the first link for the controller cookie documentation. The path can be set in the second parameter's hashref.Whereof

© 2022 - 2024 — McMap. All rights reserved.