ReactJS:如何在一个动作中正确实现react-cookie?

时间:2018-11-14 03:58:31

标签: javascript reactjs cookies

我已阅读文章,将令牌保存在localstorage中对XSS攻击很危险。因此,我决定将令牌存储在cookie中。我正在使用react-cookie。我看到了示例,但我尝试这样做,但是我的auth.jsconst组成,并且不是类,因此我不知道如何将withCookies()与它一起使用,这是我要在其中将令牌存储到cookie的auth.js

import {
  LOGIN,
  LOGIN_SUCCESS,
  LOGIN_FAILED,

  GET_USER_DATA,
  GET_USER_DATA_SUCCESS,
  GET_USER_DATA_FAILED,

  LOGOUT,
  LOGOUT_SUCCESS,
  LOGOUT_FAILED,
} from './types'

import axios from 'axios'
var api = require ('./../api.js');


export const login = (email, pass) => {
    return (dispatch) => {
        dispatch({
            type: LOGIN
        })
        var url = api.logInApi
        axios.post(url, {
              email: email,
              password: pass
            })
            .then(res => {
                dispatch({
                    type: LOGIN_SUCCESS,
                    payload: res.data
                })
                localStorage.setItem('token', res.data.token)
                dispatch(getUserData())
            })
            .catch(err => dispatch({
                type: LOGIN_FAILED,
                payload: err
            }))
    }
}



export const getUserData = () => {
    return (dispatch) => {
        dispatch({
            type: GET_USER_DATA
        })
        var url = api.getUserDataApi
        axios.post(url, {}, {headers: {
                "Authorization": `Bearer ${localStorage.getItem("token")}` 
              }})
            .then(res => {
                dispatch({
                    type: GET_USER_DATA_SUCCESS,
                    payload: res.data
                })
            })
            .catch(err => dispatch({
                type: GET_USER_DATA_FAILED,
                payload: err
            }))
    }
}


export const logout = () => {
    return (dispatch) => {
        dispatch({
            type: LOGOUT
        })
        var url = api.logoutApi
        axios.post(url, {}, {headers: {
                "Authorization": `Bearer ${localStorage.getItem("token")}` 
              }})
            .then(res => {
                window.location.replace("")
                dispatch({
                    type: LOGOUT_SUCCESS,
                    payload: res.data
                })
            })
            .catch(err => dispatch({
                type: LOGOUT_FAILED,
                payload: err
            }))
    }
}

现在,我尝试执行此操作,但它当然不起作用:

import {
  LOGIN,
  LOGIN_SUCCESS,
  LOGIN_FAILED,

  GET_USER_DATA,
  GET_USER_DATA_SUCCESS,
  GET_USER_DATA_FAILED,

  LOGOUT,
  LOGOUT_SUCCESS,
  LOGOUT_FAILED,
} from './types'

import axios from 'axios'
import { withCookies, Cookies } from 'react-cookie'; <<added this
var api = require ('./../api.js');

const login  = (email, pass) => {
    return (dispatch) => {
        dispatch({
            type: LOGIN
        })
        const { cookies } = props; <<added this
        var url = api.logInApi
        axios.post(url, {
              email: email,
              password: pass
            })
            .then(res => {
                dispatch({
                    type: LOGIN_SUCCESS,
                    payload: res.data
                })
                cookies.set('token', res.data.token, { path: '/' }); <<added this
                dispatch(getUserData())
            })
            .catch(err => dispatch({
                type: LOGIN_FAILED,
                payload: err
            }))
    }
}
export default withCookies(login) <<added this(wrong)



const getUserData = () => {
    return (dispatch) => {
        dispatch({
            type: GET_USER_DATA
        })
        const { cookies } = props; <<added this
        var token = cookies.get('token'); <<added this
        var url = api.getUserDataApi
        axios.post(url, {}, {headers: {
                "Authorization": `Bearer ${token}` <<added this(this is where I wanna get the cookie)
              }})
            .then(res => {
                dispatch({
                    type: GET_USER_DATA_SUCCESS,
                    payload: res.data
                })
            })
            .catch(err => dispatch({
                type: GET_USER_DATA_FAILED,
                payload: err
            }))
    }
}
export default withCookies(getUserData) <<added this(wrong)


const logout = () => {
    return (dispatch) => {
        dispatch({
            type: LOGOUT
        })
        const { cookies } = props;
        var token = cookies.get('token');
        var url = api.logoutApi
        axios.post(url, {}, {headers: {
            "Authorization": `Bearer ${token}` <<added this
              }})
            .then(res => {
                window.location.replace("")
                dispatch({
                    type: LOGOUT_SUCCESS,
                    payload: res.data
                })
            })
            .catch(err => dispatch({
                type: LOGOUT_FAILED,
                payload: err
            }))
    }
}
export default withCookies(logout) <<added this(wrong)

这是错误的,因为应该只有一个导出默认值。但是我不知道如何使用withCookies来实现const,示例中也包含了这些内容,我不知道是否需要它们或将它们放在哪里:

  static propTypes = {
    cookies: instanceOf(Cookies).isRequired
  };

  constructor(props) {
    super(props);

    const { cookies } = props;
    this.state = {
      name: cookies.get('name') || 'Ben'
    };
  }

还有另一个问题是,我可以在项目的任何位置访问cookie,对吗?就像我的项目如何访问localstorage一样?

我希望有人可以帮助我,对此我是新手。我以前从未使用过Cookie,因此感谢您的考虑。

1 个答案:

答案 0 :(得分:2)

我个人更愿意使用js-cookie来编写/读取cookie。

它有一个非常基本的API:

Cookie.set('cookie_name', 'value') // will set "cookie_name" to "value"
Cookie.get('cookie_name') // will return "value"

意思是:

const login  = (email, pass, cookie) => {
    return (dispatch) => {
        dispatch({
            type: LOGIN
        })
        var url = api.logInApi
        axios.post(url, {
              email: email,
              password: pass
            })
            .then(res => {
                dispatch({
                    type: LOGIN_SUCCESS,
                    payload: res.data
                })
                cookies.set('token', res.data.token);
                dispatch(getUserData())
            })
            .catch(err => dispatch({
                type: LOGIN_FAILED,
                payload: err
            }))
    }
}

在第三个参数中传递到login函数js-cookie的Cookie。

现在,您仍然可以使用相同的react-cookie包来读取Cookie值(我相信应该不会有任何冲突)。或者,您可以将其替换为js-cookie。为此,您必须将Cookie对象传递给道具。如果您使用的是mapStateToProps,或者仅通过Redux

,我可能会使用JSX