【问题标题】:Laravel with JWT Auth: Get error message with status codeLaravel with JWT Auth:获取带有状态码的错误消息
【发布时间】:2017-09-21 04:10:48
【问题描述】:

我尝试在我的 Laravel + Vue SPA 中实现 JWT Auth。

在我的控制器中,我检查像

这样的凭据
try {
        if (!$token = JWTAuth::attempt($credentials)) {
            return response()->json(
                [
                    'error' => 'Invalid Credentials',
                ], 401
            );
        }
    } catch (JWTException $e) {
        return response()->json(
            [
                'error' => 'Could not create token!',
            ]
        );
    }

    return response()->json(
        [
            'token' => $token,
        ]
    );

我的 API 调用如下所示:

axios.post('/api/user/signin', payload)
    .then((res) => {
      console.log(res)
    })
    .catch((err) => {
      console.log(err)
    })

如果我通过payload 传递有效凭据,我会在then 块中获得令牌,并可以将其记录在控制台中。

如果我传递了无效的凭据,我会在控制台中收到错误:

错误:请求失败,状态码 401 在 createError (app.js:10562) 结算时 (app.js:21378) 在 XMLHttpRequest.handleLoad (app.js:10401)

如何获得“无效凭据”错误?如果我从响应中删除状态代码或将其设置为 200,则会收到错误“Invalid Credentials”。

【问题讨论】:

    标签: javascript laravel-5 error-handling vue.js jwt


    【解决方案1】:

    您可以使用response 错误键。得到响应。

    axios.post('/api/user/signin', payload)
        .then((res) => {
          console.log(res)
        })
        .catch((err) => {
          console.log(err.response)
        })
    

    在这里查看:https://github.com/mzabriskie/axios/blob/master/UPGRADE_GUIDE.md#012x---0130

    【讨论】:

    • 天哪,我现在感觉好傻……我想,既然错误是作为字符串输出的,就没有对象……非常感谢!
    猜你喜欢
    • 2019-09-20
    • 2017-06-10
    • 2018-11-21
    • 2019-12-31
    • 2018-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多