2017-04-24 29 views
0

我尝试在我的Laravel + Vue SPA中实施JWT Auth。Laravel with 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) 
    }) 

如果我通过有效凭证与​​我得到的then块令牌和可以在控制台中记录这一点。

如果我通过无效的凭据我在控制台得到一个错误:

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

回答

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

+0

哦,我感觉很愚蠢,现在...我想,既然错误是作为一个字符串输出,没有对象......谢谢你许多! – Sebastian

+1

哈哈,发生! :d –