会话在Laravel API中不起作用 [英] Session not working in Laravel API

查看:70
本文介绍了会话在Laravel API中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,在使用网站(非API)时,我会在会话中保存临时数据/数组.

Usually I save temporary data/array inside session while working with Website (Non API).

今天我想用Laravel API做同样的事情(在会话中保存临时数据/数组).

Today I want to do the same thing (save temporary data/array inside session) with Laravel API.

这是我的路线.

Route::middleware(['auth:api', 'isMember'])->group(function () {

  Route::get('createSession', function (){
    $a = Session::put('example', 'this is example session.');
    return "session created";
  });

  Route::get('getSession', function () {
    return Session::get('example');
  });

});

当我访问/api/createSession 时,它返回 session created ,但是当我访问/api/getSession 时,它不返回任何内容.

When I visit /api/createSession it return session created, but when I visit /api/getSession it return nothing.

那我该如何在API中使用会话?

我认为为什么这不起作用,因为 API 使用基于令牌的身份验证而不是基于会话的身份验证,请参阅 config/auth.php Authentication Guards 部分.

What I think why this not work because API use Token based authentication instead of Session based Authentication, refer to config/auth.php Authentication Guards section.

如果在API内部使用会话被认为是不好的做法,那么您建议在API内部保存临时数据/数组以用于共享托管?

到目前为止,我尝试将数据/数组保存在 Storage :: disk(local)中,但是我认为这不是最佳实践.

What I have tried so far is save data/array in Storage::disk(local) but I don't think it best practice.

谢谢.

PS:我将使用会话存储有关购物车的临时数据

PS: I will use Session to store temporary data about Cart

推荐答案

中间件api不包含StartSession中间件,因此无法获取该会话.在此处检查: https://github.com/laravel/laravel/blob/master/app/Http/Kernel.php#L33

Middleware api did not include StartSession middleware, so you can not get the session. Check it here: https://github.com/laravel/laravel/blob/master/app/Http/Kernel.php#L33

您可以将中间件"web"添加到路由中,或将 \ Illuminate \ Session \ Middleware \ StartSession :: class 添加到中间件api,但我不建议这样做.API不应使用会话.

You can add middleware "web" to your route or add \Illuminate\Session\Middleware\StartSession::class, to middleware api but I'm not recommended it. APIs should not use session.

希望它可以为您提供帮助.

Hope that it can help you.

这篇关于会话在Laravel API中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆