首页 > 解决方案 > React - 将 cookie 发送到 Express

问题描述

我正在获取一个访问 API 端点的令牌,我想将此令牌发送到我的服务器端应用程序 (expressJS) 以检索数据。

我的反应应用程序有以下内容:

export default class Account extends React.Component {
    constructor() {
        super();
        this.state = {
          token: null,
          response: {

          }
        };
        this.getCurrentlyPlaying = this.getCurrentlyPlaying.bind(this);
      }
      componentDidMount() {
        // Set token
        let _token = hash.access_token;
        if (_token) {
          this.setState({
            token: _token
          });
          const cookies = new Cookies();
          cookies.set('token', _token, { path: '/' });
          console.log(cookies.get('token'));
          this.getCurrentlyPlaying(_token);
        }
      }

      getCurrentlyPlaying() {
        fetch(`http://localhost:3001/account`)
        .then(res => res.json())
        .then(data => {
          this.setState ({
              response: data
          })
          console.log(data);
        });
      }
    render() {
       if (this.state.response[0].is_playing  === true) {
        return (
          <p> Something is playing</p>
         );
       }
       else {
         return (
          <p> Nothing is playing</p>
         );
       }
    }
}

在我的快速应用程序中,我获取了 cookie,但我不确定它是否真的获取了由 react 应用程序创建的 cookie:

  router.get('/account', (req, res) => {
    const config = {
      headers: {
        'Authorization': `Bearer ${req.session.token}`
      }
    };
    fetch(`${CONFIG.spotifyUrl}/me/player/currently-playing `, config)
    .then(html => html.json())
    .then(json => {
      res.json(json);
    });
  });
module.exports = router;

有人可以告诉我哪里出错了吗?

标签: reactjsexpresscookiestokensession-cookies

解决方案


要在后端使用 express 解析 cookie,一个不错的选择是使用https://github.com/expressjs/cookie-parser中间件。

如果您使用类似于下面的设置

const cookieParser = require('cookie-parser');
app.use(cookieParser());

服务器上的每个请求对象都将在req.cookies属性中包含 cookie 信息。所以在你的情况下应该是req.cookies.token


推荐阅读