首页 > 解决方案 > 为什么除了 Laravel 中的 Ajax 之外,我无法通过普通浏览器请求读取 cookie 的值?

问题描述

我在 Ajax 上设置了一个 cookie,但我无法在视图中读取它的值;我可以通过 Ajax 完成。

这发生在 Laravel 5.8 上。

所以,基本上,在 routes/web.php 我有这个功能:

Route::get("/sample", function () {
  echo \Illuminate\Support\Facades\Cookie::get('verified_cli');
});

并且在 routes/api.php 中的功能基本相同:

Route::get("/sample", function () {
  return \Illuminate\Support\Facades\Cookie::get('verified_cli');
});

来自 api.php 的一个有价值,但另一个没有。

这是我在中间件中用于设置 cookie 的代码(在 Ajax 中):

public function handle(Request $request, Closure $next) {
    $response = $next($request);
    return $response->withCookie(Cookie::make('verified_cli', $value, 900));
}

我希望能够在 Ajax 上设置 cookie,并能够在视图和 Ajax 中读取它。目前,我只能读取 Ajax 上的 cookie 值。

谢谢。

标签: phplaravelcookies

解决方案


我想到了。

如果您通过 Ajax 设置 cookie,则必须对 cookie 进行加密,尤其是如果您希望它可以通过 Web 访问。这对我有用。

Ajax 调用的一些中间件:

return response('another response')->
       cookie("some_cookie", \Crypt::encryptString("Some cotent"), 100);

推荐阅读