【问题标题】:Validating authorized & Unauthorized User (JWT ReactJS-Laravel)验证授权和未授权用户 (JWT ReactJS-Laravel)
【发布时间】:2019-03-07 06:32:51
【问题描述】:

我目前正在做登录页面。在将令牌设置为本地存储之前,我对如何检查我登录的用户是有效还是无效有疑问。

我的控制台出错:

POST http://localhost:8000/api/auth/login 401(未授权)

未捕获(承诺中)错误:请求失败,状态码为 401

我的目标: 如果用户有效,则重定向到其他页面,如果无效,则进入的用户将保留在登录页面上。

我使用 Axios.post 发出请求

我这里有 handleSubmit 按钮:

handleSubmit(e) {
    e.preventDefault();

    axios.post('/api/auth/login',this.state).then(response => {
        const token_id = response.data.access_token;
        const responsed = response.data;
        // localStorage.setItem('token', token_id);
        console.log(responsed);
    });

   

}

这是我的函数,它是 JWT 文档中的默认函数:

public function login(Request $request)
{
    $credentials = $request->only('email', 'password');

    if ($token = $this->guard()->attempt($credentials)) {
        return $this->respondWithToken($token);
    }

    return response()->json(['error' => 'Unauthorized'], 401);
}

【问题讨论】:

  • 你在用vue路由器吗?
  • 我已经解决了这个问题 :) 谢谢罗斯。
  • 好的,罗斯,谢谢,我会添加答案

标签: reactjs laravel jwt


【解决方案1】:

验证登录用户

我只是添加条件。

handleSubmit(e) {
    e.preventDefault();

    axios.post('/api/auth/login',this.state).then(response => {

        const token_id = response.data.access_token;


        localStorage.setItem('token', token_id);
        var get_token = localStorage.getItem('token');

        if(get_token === null)
        {   
            return <Redirect to='/login'  />
        }
        else
        {
            this.props.history.push('/hiflyer-dashboard');
        }

    }).catch((error) =>{
        if(error.response)
        {
            alert('Invalid');
        }
    })



}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-08
    • 2017-09-11
    • 2021-07-17
    • 2017-07-21
    • 2011-04-17
    • 1970-01-01
    • 2017-06-12
    • 2020-10-29
    相关资源
    最近更新 更多