Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting cookies in mojolicious response

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.

like image 380
PMat Avatar asked Mar 07 '12 21:03

PMat


Video Answer


1 Answers

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

like image 75
tempire Avatar answered Sep 30 '22 05:09

tempire