如何在React中使用多个axios请求实现jwt令牌并保存数据

时间:2019-03-30 14:31:11

标签: reactjs redux react-redux

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

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

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));}

刷新浏览器时,我需要获取两个数据。我该怎么解决?

0 个答案:

没有答案