【问题标题】:Laravel API call goes through even with session expired即使会话过期,Laravel API 调用也会继续
【发布时间】:2019-10-27 03:49:42
【问题描述】:

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

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

这是我的设置。

web.php 是我唯一指向singlePageController 的php 路由:

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);
        })

提前感谢您的帮助

【问题讨论】:

  • 当你说你“删除会话”时,你具体是怎么做的,客户端和后端之间的身份验证是如何处理的?您是否只使用 API 令牌、JWT 等?
  • 我只使用基本的 Laravel Auth。没有 JWT 或 Passport。当我删除会话时,我只是从 Chrome 开发工具中删除它

标签: laravel api vue.js single-page-application


【解决方案1】:

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

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

【讨论】:

  • 现在我登录 LOL 时都无法保存……它告诉我“不允许使用 405 方法”我正在使用 PUT 作为请求方法
  • 您是否更新了 vue 中的路线以匹配新位置? Web 路由不像 api 路由那样使用 /api/ 前缀。
猜你喜欢
  • 2017-03-29
  • 2016-05-20
  • 2017-09-17
  • 1970-01-01
  • 2012-08-17
  • 2017-11-08
  • 1970-01-01
  • 2018-03-29
  • 2011-07-27
相关资源
最近更新 更多