【问题标题】:React - Send cookie to ExpressReact - 将 cookie 发送到 Express
【发布时间】:2020-08-14 11:10:44
【问题描述】:

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

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

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>
         );
       }
    }
}

在我的 express 应用程序中,我获取了 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;

谁能告诉我哪里出错了?

【问题讨论】:

  • 使用 document.cookie 设置 cookie。参考这个developer.mozilla.org/en-US/docs/Web/API/Document/cookie
  • @chandan_kr_jha 它正确设置了 cookie,因为当我有 cookie 的 console.log() 时,我看到它显示了。我正在使用 'react-cookie- 包。
  • 在 express js 的日志中看到了什么。请参阅stackoverflow.com/questions/44816519/…。你在 expressjs 中使用 cookie-parser。如果没有尝试第二个答案。 cookie 将在标题中。
  • 我的 app.js 文件中有app.use(cookieParser());
  • @chandan_kr_jha 我正在做类似问题中提到的事情,但它仍然无法为我获取。它也没有显示任何奇怪的错误

标签: reactjs express cookies token session-cookies


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 2023-03-30
    • 2021-03-05
    • 2021-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-17
    • 1970-01-01
    • 2021-07-18
    相关资源
    最近更新 更多