javascript - Laravel 与 JWT Auth : Get error message with status code

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

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

在我的 Controller 中,我检查凭据,例如

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 block 中获得 token ,并可以将其记录在控制台中。

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

Error: Request failed with status code 401 at createError (app.js:10562) at settle (app.js:21378) at XMLHttpRequest.handleLoad (app.js:10401)

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

Error with Status

最佳答案

您可以使用错误的响应键。以获得响应。

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

关于javascript - Laravel 与 JWT Auth : Get error message with status code,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43588753/

相关文章:

php - 在 laravel 5.3 中实现命名空间

php - Laravel:不允许写入/.../.config/psysh

css - 语法错误 : unexpected token ""

unity3d - Unity VRTK Assets 错误

javascript - 将div的面积缩小为一个圆圈?

javascript - 原型(prototype)与 JavaScript 中的应用

javascript - SonarQube、sonar-javascript 和 JS TestDriver - 找不到资源

laravel - 从 Laravel Blade 上的字符串中删除 HTML 标签

javascript - 如何让我的弹出图像继续显示?

gradle - 位置信息包出现错误。怎么修?