访问响应代码中的响应对象以获取cookie的值

时间:2017-06-09 18:22:38

标签: reactjs cookies webpack

所以我有一些反应代码,我正在用webpack编译。此代码的一部分包括获取用于通过JSON Web令牌进行身份验证的cookie的值。我遇到的问题是我无法访问响应变量。任何帮助都会很棒,谢谢!

var Cookies = require('cookies');
var cookieParser = require('cookie-parser');

var React = require('react');
var ReactDOM = require('react-dom');
import { Router, Route, browserHistory, Link } from 'react-router';

import 'whatwg-fetch'

var name = document.getElementById('name').innerHTML;   



  var start = false;
  var Assets = React.createClass({
    getInitialState: function(){
      return {
        assets: [],
        secondsElapsed: 0
      }
    },
    tick: function() {
      if(start === true){
        console.log(name);

        var myHeaders = new Headers();

        var token = new Cookies(req,res).get('access_token'); //NEED ACCESS TO RES HERE

        myHeaders.append('acess_token', token);

        var myInit = { method: 'GET',
               headers: myHeaders};

        fetch('/api/user/all/?name='+name, myInit).then(function(data){
          return data.json();
        }).then( json => {
          this.setState({
              assets: json
            });
        });
    }
    },
    componentDidMount: function() {
      this.interval = setInterval(this.tick, 1000);
    },
    componentWillUnmount: function() {
      clearInterval(this.interval);
    },
    render: function(){
      var assets = this.state.assets;
      assets = assets.map(function(asseti,index){
        return(
          asseti.map(function(asset, index){
            return(
              <li key={index}>
                        <span className={asset.active}></span>
                        <span>{asset.name}</span>
                        <span >{asset.description}</span>
              </li>
            )
          })
        )
      });
      return(
        <div>
          <form onSubmit={this.handleSubmit}>
            <input type="submit" value="Find assets" />
          </form>
          {assets}
        </div>
      );
    },
    handleSubmit: function(e){
      e.preventDefault();
      start = true;

      fetch('/api/user/all/?name='+name).then(function(data){
        return data.json();
      }).then( json => {
        this.setState({
          assets: json
        });
      });
    }
  });

ReactDOM.render(<Assets />, document.getElementById('assets'));

1 个答案:

答案 0 :(得分:0)

毫无疑问,OP早已找到解决方案。我在React中确实是一个菜鸟,但为了任何阅读此内容并希望使用该框架访问cookie的人的利益:https://github.com/reactivestack/cookies

我欢迎任何反馈意见,并希望了解它是如何适合你的。