How to attach cookies to JSON Response in symfony2?

血红的双手。 提交于 2021-02-07 19:12:14

问题


I have JSON endpoint which is used to add product to cart. It checks whether the cart already exists or no. If not then it creates a cart and the cart Id is stored in cookie. So I how do I attach cookie to the symfony2's JsonResponse ?

In a non ajax version if I am rendering a template from my action I can use:

$response = new Response();
$response->headers->setCookie(new Cookie(‘cookie_name’, ‘cookie_value’));

$this->render('<template_path>', '<array_options>', $response);

Please help me on how to do it for a JsonResponse.


回答1:


In my opinion, you will find the answer under the following links:

How can i send json response in symfony2 controller

http://api.symfony.com/2.2/Symfony/Component/HttpFoundation/JsonResponse.html

http://symfony.com/doc/current/components/http_foundation/introduction.html

The best way, to see links and learn, but if you will not find the answer, maybe this will be good:

use Symfony\Component\HttpFoundation\Response;

$response = new Response();
$response->headers->set('Content-Type', 'application/json');
$response->headers->setCookie(new Cookie(‘cookie_name’, ‘cookie_value’));

return $response;

There is also a helpful JsonResponse class, which can make this even easier:

use Symfony\Component\HttpFoundation\JsonResponse;

$response = new JsonResponse();
$response->headers->setCookie(new Cookie(‘cookie_name’, ‘cookie_value’));

return $response;

I hope, this will be helpfull :)



来源:https://stackoverflow.com/questions/20626099/how-to-attach-cookies-to-json-response-in-symfony2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!