[英]Laravel package session variable not saving with ajax call
我正在构建一个名为under-construction
的包。 在配置文件中激活此程序包时,只有拥有正确代码的人才能访问该应用程序。
https://github.com/larsjanssen6/underconstruction
我现在遇到的问题:
当输入代码时,我做了一个ajax调用,命中了这个控制器方法(称为check ):
https://github.com/larsjanssen6/underconstruction/blob/master/src/Controllers/CodeController.php
如果代码正确,则设置会话变量:
session(['can_visit' => true]);
然后在我的vue.js代码中,我重定向到/
。 它会再次击中我的中间件。 在这里,我检查是否存在名为can_visit
的会话。
return session()->has('can_visit');
https://github.com/larsjanssen6/underconstruction/blob/master/src/UnderConstruction.php
但会话变量can_visit
总是不见了! 怎么可能?
谢谢你的时间。
您没有加载会话中间件,因此会话未启动且没有值持久存在。
正如评论中提到的,即使您的受保护路由( /
)位于Web中间件(读取会话)中,您的服务提供商的路由( /under/construction
, /under/check
)也不是(无写入会话)。
简单的解决方法是添加会话,甚至更好的整个Web中间件。
$routeConfig = [
'namespace' => 'LarsJanssen\UnderConstruction\Controllers',
'prefix' => 'under',
'middleware' => [
'web', // add this
// DebugbarEnabled::class, // leaving this dead code behind despite vcs
],
];
但是,如果用户将中间件添加到其Web中间件组,您可能会很快遇到无限重定向循环的问题。 所以,我想补充某种形式的检查,以确保你不是在现有的一个underconstruction
路线。
public function handle($request, Closure $next)
{
// check this isn't one of our routes
// too bad router hasn't loaded named routes at this stage in pipeline yet :(
// let's hope it doesn't conflict with user's routes
if ($request->is('under/*')) {
return $next($request);
}
if (! $this->config['enabled']) {
return $next($request);
}
if (!$this->hasAccess($request)) {
return new RedirectResponse('/under/construction');
}
return $next($request);
}
最后从这个项目的背景中猜测,我希望大多数人都想在全球中间件中坚持这一点。 但是,您将遇到相同的会话 - 尚未启动的问题,因为它不会在全局中间件中运行。 所以还有更多可以咀嚼的东西。 快乐的编码!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.