react 获取token

Posted guangzhou11

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了react 获取token相关的知识,希望对你有一定的参考价值。

1.在action  中发送请求,j将获取得到的token  储存起来 到localhost

//登陆发送请求
export  const  loginUser = (userData,history)=>dispatch=>{
    
      axios.post("/api/user/login",userData)
      .then(res=>{
            const  { token }=res.data;
            console.log(token);
            //储存token到local
            localStorage.setItem("jwtToken",token);
            //设置axios  的header
            setAuthToken(token);
      })
      .catch(err=>{
            dispatch({
                type:GET_ERRORS,
                payload:err.response.data
            }) 
      })
}

  2.登陆主页面中将action  与  登陆组件连接起来

import React, { Component } from ‘react‘
import {loginUser} from ‘../../actions/authActions‘
import {connect} from ‘react-redux‘
import {withRouter} from ‘react-router-dom‘
 class Login extends Component {
  constructor() {
    super();
    this.state = {
      email: ‘‘,
      password: ‘‘,
      errors: {}
    };

    this.onChange = this.onChange.bind(this);
    this.onSubmit = this.onSubmit.bind(this);
  }

  onChange(e) {
    this.setState({ [e.target.name]: e.target.value });
  }
  onSubmit(e) {
    e.preventDefault();
    const newUser = {
      email: this.state.email,
      password: this.state.password
    };
    // console.log(newUser);
    this.props.loginUser(newUser)
  }
  render() {
    return (
      <div className="login">
      <div className="container">
        <div className="row">
          <div className="col-md-8 m-auto">
            <h1 className="display-4 text-center">登录</h1>
            <p className="lead text-center">使用已有的账户登录</p>
            <form onSubmit={this.onSubmit}>
            <div  className="form-group">
                  <input
                    type="email"
                    className="form-control  form-control-lg"
                    placeholder="邮箱地址"
                    name="email"
                    value={this.state.email}
                    onChange={this.onChange}
                  />
             </div>
             <div  className="form-group">
                    <input
                      type="password"
                      className="form-control  form-control-lg"
                      placeholder="密码"
                      name="password"
                      value={this.state.password}
                      onChange={this.onChange}
                    
                    />
              </div>
              <input type="submit" className="btn btn-info btn-block mt-4" />
            </form>
          </div>
        </div>
      </div>
    </div>
    )
  }
}
//connect  将两个组件连接起来
export default connect(null,{loginUser})(withRouter(Login))

  3.设置axios 的header

import axios from ‘axios‘;

const setAuthToken = token => {
  if (token) {
    // headers 每个请求都需要用到的
    axios.defaults.headers.common["Authorization"] = token;
  } else {
    delete axios.defaults.headers.common["Authorization"];
  }
}

export default setAuthToken;

  4.效果显示

技术分享图片

以上是关于react 获取token的主要内容,如果未能解决你的问题,请参考以下文章

PayPal REST API 获取 react-native 中的 access_token,“AUTHENTICATION_FAILURE”

获取错误:-S SyntaxError: Unexpected token < in JSON at position 0 REACT

从现有的 id_token 获取 Auth0 access_token

add application window with unknown token XXX Unable to add window;is your activity is running?(代码片段

add application window with unknown token XXX Unable to add window;is your activity is running?(代码片段

React-umi-request动态刷新Token功能实现及node.js 代码逻辑