在Laravel中检索Session值将返回null

时间:2018-10-27 17:44:08

标签: php laravel session vuejs2 session-variables

我正在设置并尝试从Laravel应用程序中检索会话值。 Vue Js前端正在对设置会话值的Laravel端点进行API调用。包含Laravel端点方法的控制器为:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
Use Session;

use App\User;

class UserController extends Controller
{
    public function adduser(Request $request) {

        $user = User::where( 'sub', $request->sub )->first();

        if(!$user) {

            $user = new User();

            $user->nickname = $request->nickname;
            $user->name = $request->name;
            $user->sub = $request->sub;
            $user->api_token = $request->api_token;

            $user->save();

        }

        $user->api_token = $request->api_token;
        $user->save();

        return response()
            ->json([
                'done' => $user->api_token
            ]);

    }

    //The endpoint for this method is http://localhost:8000/api/set
    public function setSession(Request $request) {


        $request->session()->put('info', 'testing vue client again');
        Session::save();

        return response()
            ->json([
                'done' => session('info')
            ]);

    }
    //The endpoint for this method is: http://localhost:8000/api/get
    public function getSession(Request $request) {

        $value = $request->session()->get('info');
        return response()
            ->json([
                'done' => $value
            ]);

    }

}

会话数据已成功设置,但是当我尝试从getSession()方法检索此数据时,它将返回null。这是我用来尝试检索会话数据的Vue Js / axios代码片段

axios({
 method: 'get',
 url: 'http://localhost:8000/api/get',


}).then((res) => {
console.log(res.data)
})

如何解决此问题?谢谢

2 个答案:

答案 0 :(得分:0)

默认情况下,来自routes / api.php文件的路由没有<header>I want this header to remain sticky</header> <div class="scale"> But I don't want this div to resize the x-axis of the viewport. </div>中间件,因为api调用被认为是无状态的。您可以按照以下顺序将带有StartSession的中间件添加到EncryptCookies文件中的api中间件组中,具体顺序如下:

app/Http/Kernel.php

为我工作。另外,您可以根据自己的情况将protected $middlewareGroups = [ 'web' => [ \App\Http\Middleware\EncryptCookies::class, \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, \Illuminate\Session\Middleware\StartSession::class, // \Illuminate\Session\Middleware\AuthenticateSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, \App\Http\Middleware\VerifyCsrfToken::class, \Illuminate\Routing\Middleware\SubstituteBindings::class, ], 'api' => [ \App\Http\Middleware\EncryptCookies::class, \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, \Illuminate\Session\Middleware\StartSession::class, 'throttle:60,1', 'bindings', ], ]; 组设置为api组。

别忘了用新的配置再次设置会话变量。

答案 1 :(得分:0)

我重现了该问题,并且似乎Cookie出现了问题。 这对我有用:

app \ Http \ Middleware \ EncryptCookies.php

protected $except = [
    'laravel_session',
];

laravel_session更改为您的config('session.cookie')值。

请参见Session ID changes on refresh (Laravel 5.4 + AngularJS 1.6)