Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS How To Set Cookie From Fetch Request to Back End

I have a react front end that is talking to a Node Back End. I am able to make requests and such . However, I noticed that I cannot set the cookie that I am getting back. My back end will respond upon logging in, with a message and a cookie. How should I be doing this?

Relevant code:

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

I had to add this to make the answer below applicable :
npm install react-cookies --save
import cookie from 'react-cookies'

Here is my code after.

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

    }
like image 331
LUser Avatar asked Jun 18 '17 10:06

LUser


2 Answers

What you are doing is not setting the cookie. You are just creating a variable in state called cookie.

Install this package.

The correct syntax is

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

Now it is actually stored in to your browser cookies. You can go ahead and access it back using

Cookies.get('access_token')
like image 168
Aftab Khan Avatar answered Sep 19 '22 12:09

Aftab Khan


For react you can also use react-cookie package. And if the React version >16.8.0 you can use React Hooks.

import { useCookies } from 'react-cookie';
const [cookies, setCookie] = useCookies(['name']); // getting react hooks
cookie2.set('access_token', 'content of cookie');
cookie = cookies.get('access_token');
console.log(cookie)
like image 24
Trect Avatar answered Sep 22 '22 12:09

Trect