ReactJS如何设置从获取请求到后端的Cookie

Qnd*_*del 2 authentication cookies login reactjs es6-promise

我有一个与节点后端通信的React前端。我可以提出这样的要求。但是,我注意到我无法设置要返回的cookie。我的后端将在登录后响应,并显示一条消息和一个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>
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

我必须添加它才能使以下答案适用:
npm install react-cookies-
从'react-cookies'保存导入cookie

这是我的代码。

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

    }
Run Code Online (Sandbox Code Playgroud)

Aft*_*han 5

您正在执行的操作不是设置cookie。您只是在创建状态为cookie的变量。

安装软件包。

正确的语法是

Cookies.set('access_token', response.headers['x-access-token'])
Run Code Online (Sandbox Code Playgroud)

现在,它实际上存储在您的浏览器cookie中。您可以继续使用并重新访问它

Cookies.get('access_token')
Run Code Online (Sandbox Code Playgroud)