2017-06-18 199 views
0

我有一个正在与节点后端交谈的反应前端。我能够提出请求等。不过,我注意到我无法设置我回来的cookie。我的后端将在登录时作出响应,并附带一条消息和一个cookie。我应该怎么做?ReactJS如何将Cookie从提取请求设置为后端

相关代码:

import React from "react"; 
import Fetch from 'react-fetch'; 

export class Loginform extends React.Component{ 
    constructor(){ 
    super(); 
    this.state = {message : ""}; 
    this.state = {cookie : ""}; 
    } 

    Login(e){ 
    e.preventDefault(); 
    var Email_Address = this.refs.Email.value; 
    var Password  = this.refs.Password.value; 

    fetch("http://localhost:5000/api/form", { 
     method: "POST", 
     headers: { 
      "Content-Type":"application/json", 
      "Accept":"application/json" 
     },credentials: "include", 
     body: JSON.stringify({ 
      Email_Address: Email_Address, 
      Password: Password 
     }) 
     }).then(response=>response.json()) 
     .then(response => this.setState({message: response.Message, cookie :response['x-access-token']})); 
    } 

    render(){ 
     return(
    <div className="LoginContainer"> 
    <form name="Loginform" method="post" action="http://localhost:5000/api/tavern" onSubmit={this.Login.bind(this)}> 
    <div className="block"> 
    <label><i className="fa fa-envelope"></i></label> 
    <input ref="Email" type="email" placeholder="E-Mail" required title="Enter Valid E-Mail Address"/> 
    <i className="fa fa-check" aria-hidden="true"></i> 
    </div> 
    <div className="block"> 
    <label><i className="fa fa-lock"></i></label> 
    <input ref="Password" type="password" placeholder="Enter Your Password" pattern=".{9,}" required title="9 Characters Minimum"/> 
    <i className="fa fa-check" aria-hidden="true"></i> 

    </div> 
    <div className="returnmessage"> {this.state.message}</div> 
    <div className="buttons"> <button type="submit" value="Submit">Login</button></div> 
    </form> 
    </div> 
     ); 
    } 
} 

我不得不添加此作出以下适用的答案:
NPM安装反应饼干--save
进口饼干从“反应饼干”

这是我的代码之后。

fetch("http://localhost:5000/api/tavern", { 
     method: "POST", 
     headers: { 
      "Content-Type":"application/json", 
      "Accept":"application/json" 
     },credentials: "include", 
     body: JSON.stringify({ 
      Email_Address: Email_Address, 
      Password: Password 
     }) 
     }).then(response=>response.json()) 
     .then(function (data){ 
      console.log(data); 
      cookie.save('x-access-token', data['x-access-token']); 
      this.setState({message: data.Message, cookie :data['x-access-token']}) 
     }.bind(this) 
    ) 

    } 

回答

2

你在做什么不是设置cookie。你只是在称为cookie的状态下创建一个变量。

安装this包。

正确的语法是

Cookies.set('access_token', response.headers['x-access-token']) 

现在,它实际上是存储在您的浏览器cookie。您可以继续并使用

Cookies.get('access_token') 
+0

cookie未定义。我是否需要为此安装任何软件包? – ApertureSecurity

+0

我用这个答案解决了这个问题。但是,我会在我的问题中添加一些细节。 – ApertureSecurity

+0

对不起,我忘了提包更新了答案。 –