【问题标题】:How to handle TokenMistmatchException in axios如何处理 axios 中的 TokenMismatchException
【发布时间】:2019-10-17 22:46:24
【问题描述】:

当页面停留太久直到会话变量过期时,会发生令牌不匹配...

我可以在正常 laravel 刀片文件中的异常下处理 handler.php 中的此异常,但在 vue.js 中使用 axios post 请求处理此错误时遇到问题。

我尝试过使用

try..catch (TokenMistsmatchException $e)

但我仍然无法在我的 axios 响应回调中获得 json 响应。

我正在尝试通过这些方式找到解决方案

  1. 要么我找到一种方法来在异常被触发之前过期时刷新令牌

  2. 为了得到对我的 axios 回调的响应,所以我从我的 vue 模板中重新加载页面。

您的帮助将不胜感激

【问题讨论】:

    标签: laravel exception vuejs2 axios


    【解决方案1】:

    在你的 app/Exceptions/Handler.php 文件中

    在渲染方法中为 TokenMismatchException 添加一个处理程序

    public function render($request, Exception $exception)
    {
    if ($exception instanceof \Illuminate\Session\TokenMismatchException) {
        if ($request->expectsJson()) {
            return response()->json([
                'error' => 'Token mismatch'
            ], $exception->getStatusCode());
        };
    }
    
    return parent::render($request, $exception);
    }
    

    在此之后,您可以在 axios 中捕获错误,例如

    axios.post(pathname", { body:body })
         .catch(error => {
             handle error / Display error message
         })
         .then(({ data }) => {
             If successfully request performed
         });
    

    【讨论】:

    • 你刚刚解决了我的问题,谢谢!无论如何,我无法在 catch 回调中得到错误,但在主要响应中,工作完成后没有任何问题,谢谢。
    • 你刚刚解决了我的问题,谢谢!无论如何,我无法在 catch 回调中得到错误,但在主要响应中,工作完成后没有任何问题,谢谢。
    • 乐于助人:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-21
    • 2016-05-23
    • 1970-01-01
    • 2017-10-02
    • 2020-07-08
    • 2021-03-10
    • 2021-02-19
    相关资源
    最近更新 更多