0

我正在尝试使用js-cookie在React应用程序中设置一个有效期为 10 天的 cookie 。我跟着这个文档,但是当我重新加载页面时,cookie的值总是。我希望它能保持我设置的值 10 天。undefined

这是我设置 cookie 的代码:

handleClick() {
    const axios = require('axios');
    axios.post('http://127.0.0.1:8000/es/api/login/',
      {
        username: 'admin@admin.com',
        password: 'Cancun10!',
        //username: this.state.email,
        //password: this.state.password.password,
      },
    )
    .then(function (response) {
      Cookies.set('x-xsrf-token', response.token, {expires: 10});
      console.log(response);
    })
    .catch(function (error) {
      console.log(error);
    })
  }

这是我获取 cookie 值的代码:

class App extends Component {
  render() {
    var csrfCookie = Cookies.get('x-xsrf-token')
    if(csrfCookie === 'undefined'){
      return (
        <div className="App">
          <LoginModal />
        </div>
      );
    } else {
      return (
        <div className="App">
          <Albums />
        </div>
      )
    }
  }
}

export default App;

我希望 ifLoginModal第一次发送,但之后Albums每次发送,持续 10 天。

4

1 回答 1

0

我发现了错误。cookie 没问题,但我将 cookie 的值与 进行'undefined'比较,但我必须将其与undefined. 一旦我改变了这样的条件:if(csrfCookie === undefined),一切正常。

于 2019-01-09T15:05:18.800 回答