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.效果显示

posted @ 2019-01-28 20:11  1点  阅读(4041)  评论(0编辑  收藏  举报