首页 > 解决方案 > 即使会话过期,Laravel API 调用也会继续

问题描述

我有一个基于 Laravel 5.8 和 Vue 2.0 的 SPA。

一切正常,说实话有点过头了,因为如果我删除会话,然后尝试保存内容或继续浏览私人页面,我使用 Axios 进行的每个 ajax 调用都会通过而不会返回任何错误。只有当我强制刷新页面时,我才会得到我设置的错误页面,但如果我不这样做,即使会话不再存在,我也可以继续做所有事情。

这是我的设置。

web.php是我唯一指向 a 的 php 路由的地方singlePageController

Auth::routes();

Route::get('/{any}', 'SinglePageController@index')->where('any', '.*');

然后在singlePageController我返回视图:

class SinglePageController extends Controller
    {
        public function index() {
        return view('app', ['loggedUser' => auth()->user()]);
    }
}

然后我有api.php我有 API 路由的地方。正如你在最后看到的,我有中间件将其设为私有。举个例子,这是我用来更新内容的例子:

Route::put('event/update/{slug}', 'EventController@update')->middleware('auth:api');

然后该 API 路由的相关控制器:

public function update(Request $request, $slug)
{
    $event = Event::where('slug', $slug)->first();

    $event->title = $request->input('title');

    return new EventResource($event);
 }

最后,这是我用来定义 API 数据将显示什么以及如何显示的资源:

public function toArray($request)
{
    // return parent::toArray($request);

    return [
        'id' => $this->id,
        'title' => $this->title,
        'slug' => $this->slug,
        'curator' => $this->curator,
        'featured_image' => $this->featured_image,
        'body' => $this->body,
        'date' => $this->date
    ];
 }

所以上面是我的流程。然后,当我进行 axios 调用以更新内容时,我正在执行以下操作:

    axios({
            method: 'PUT',
            url: '/api/event/update/' + this.$route.params.slug + '?api_token=' + this.isLogged.apiToken,
            data: dataToSave,
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        })  
        .then((response) => {
            this.getNotification('Success: The Event has been saved');
        })
        .catch((error) => {
            this.getNotification('Error: Impossible saving the event');
            console.log(error);
        })

在此先感谢您的帮助

标签: laravelapivue.jssingle-page-application

解决方案


在 api.php 中的 Laravel 路由中忽略会话数据。

如果您想使用会话数据进行身份验证,您可以将您的 api 路由移动到 web.php,您应该会看到您期望的结果。


推荐阅读