Oth*_*ufi 0 php cookies setcookie symfony reactjs
我正在编写一个应用程序,该应用程序使用 ReactJs 作为localhost:3001 的前端,使用 Symfony 作为后端localhost:3000,并且为了启用跨源通信,我在 Symfony 中使用“cors-bundle”。现在我想在用户登录时创建一个Cookie,但它似乎没有创建!
感谢您的帮助,
这是用户登录时 Symfony 中的代码:
use Symfony\Component\HttpFoundation\Cookie;
$cookie = new Cookie( 'my_cookie', 1, strtotime('tomorrow') );
$res = new Response();
$res->headers->setCookie( $cookie );
return new JsonResponse($res);
Run Code Online (Sandbox Code Playgroud)
这也是我尝试过的:
$res->headers->setCookie(Cookie::create('my_cookie', 1));
return new JsonResponse($res);
Run Code Online (Sandbox Code Playgroud)
你需要的是:
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
class YourClass extends AbstractController {
public function yourMethod(Request $request) {
$cookie = new Cookie(
"cookie_name_here", // Cookie name
1, // Cookie content
(new DateTime('now'))->modify("+1 day"), // Expiration date
"/", // Path
"localhost", // Domain
$request->getScheme() === 'https', // Secure
false, // HttpOnly
true, // Raw
'Strict' // SameSite policy
);
$res = new JsonResponse();
$res->headers->setCookie($cookie);
return $res;
}
}
Run Code Online (Sandbox Code Playgroud)
这里需要注意的事项。
设置“安全”标志意味着此 cookie 仅在 HTTPS 连接上传输。在生产中不要忽视这一点。您可能想用作$request->getScheme() === 'https'
参数评估。
“HttpOnly”标志是为了安全起见,并阻止 Javascipt 和浏览器扩展访问 cookie。如果您使用 XHR 发出请求(例如 Axios)并包含“withCredentials”,那么可以设置为true
并且无论如何都会发送。如果你想读取React 中的值,请将其设置为false