8

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.

PMat
  • 1,761
  • 2
  • 24
  • 41

1 Answers1

14

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

tempire
  • 2,253
  • 19
  • 14
  • 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. – PMat Mar 07 '12 at 21:48
  • Yes - the first part of the answer. – tempire Mar 07 '12 at 21:54
  • 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'); – PMat Mar 08 '12 at 21:28
  • 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. – tempire Mar 09 '12 at 19:27