首页 > 解决方案 > react中如何使用多个axios请求实现jwt token并保存数据

问题描述

如果用户提供电子邮件和密码。它将给出输入:{token:"asdfasd", auth: 'auth"}。如果用户被授权,它将调用第二个 api 提供一定量的数据,否则,它将返回 unauth

最初,我第一次得到两个数据,但是当我刷新时,我没有在减速器中看到我的第二个数据,并且我的身份验证是未经授权的。

compententDidmount(){
 this.props.loginuser()
}

export const loginUser = userData => dispatch => {

axios
 .get('/api/users/login', params:{userdata:userdata})
 .then(res => {

  // Save to localStorage
  const { token } = res.data;

  // Set token to ls
  localStorage.setItem('jwtToken', token);

  // Set token to Auth header
  setAuthToken(token);

  // Decode token to get user data
  const decoded = jwt_decode(token);

  // Set current user
  dispatch(setCurrentUser(decoded));

  if(res.data.authorized === "authorized"){

   axios.get('2nd api', {params:{user:userdata.email}}).then(res=> {

    console.log(res.data) //authorized
})} else {
      console.log(res.data) // unauthorized }
})};

// Check for token
if (localStorage.jwtToken) {

// Set auth token header auth

setAuthToken(localStorage.jwtToken);

// Decode token and get user info and exp

const decoded = jwt_decode(localStorage.jwtToken);

// Set user and isAuthenticated
store.dispatch(setCurrentUser(decoded));}

刷新浏览器时需要获取两个数据。我该如何解决这个问题?

标签: reactjsreduxreact-redux

解决方案


推荐阅读