【问题标题】:Why can't I read the value of a cookie over a normal browser request except Ajax in Laravel?为什么除了 Laravel 中的 Ajax 之外,我无法通过普通浏览器请求读取 cookie 的值?
【发布时间】:2019-05-21 18:26:54
【问题描述】:

我在 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 值。

谢谢。

【问题讨论】:

  • 会不会是 cookie 主机问题?例如api.yourdomain.com vs www.yourdomain.com

标签: php laravel cookies


【解决方案1】:

我想通了。

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

Ajax 调用的一些中间件:

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

【讨论】:

    猜你喜欢
    • 2016-02-29
    • 2012-01-30
    • 1970-01-01
    • 2011-08-17
    • 2011-05-24
    • 2016-05-09
    • 2012-12-22
    • 2022-09-30
    • 2014-04-21
    相关资源
    最近更新 更多