0

Explanation of the question

  1. when i run from server side that means from htpp://localhost:3001 then cookie saving in my brower till now no problme
  2. on reverse i called it from client side const result = await Axios({ method: "post", url: "http://localhost:3001/signin", data: { email, password}, headers: { 'Content-Type': 'application/json'} }); and sent it resquest to server side and all function on server side working no problem except cookie

i wants to save my cookie on browser when i calls request from client side for checking this i just write ` res.cookie('jwtoken',"raushan");' but this is not working please help with the code .

this is the client side login.jsx from this client side i called route for server side that means when user login i want to save cookie in the browser . i am trying this from last 3 days but till now , i am unable to find some good solution .

// import React from 'react'
import "./login.css";
import React, { useState} from "react";
import { useHistory } from "react-router-dom";

import Axios from "axios";

function Login() {
  let history = useHistory();
  const [user, Setuser] = useState({
    email: "",
    password: "",
  });
  let name, value;
  const handleinput = async (e) => {
    name = e.target.name;
    value = e.target.value;
    Setuser({ ...user, [name]: value });
  };

  const handle = async (e) => {
    e.preventDefault();
    console.log("Enter in the login formate");
    const { email, password } = user;
    try {
      const result = await Axios({
        method: "post", //you can set what request you want to be
        url: "http://localhost:3001/signin",
        data: { email, password},
         headers: { 'Content-Type': 'application/json'}
      });
      console.log(result);
      // const data=await result.json();
      if(result.status===400 )
      {
        window.alert('invalid credentials');
      }
      else
      {
        window.alert('login successfully');
        history.push('/');
      }
    } catch (error) {
      console.log(error);
    }
  };

  return (
    <>
      <div className="login">Login your acccount</div>
      <form method="post">
        <input
          type="email"
          name="email"
          id="email"
          placeholder="enter your email"
          value={user.email}
          onChange={handleinput}
        />
        <input
          type="password"
          name="password"
          id="password"
          placeholder="Enter your password"
          value={user.password}
          onChange={handleinput}
        />

        <button type="submit" onClick={handle}>
          submit
        </button>
      </form>
    </>
  );
}

export default Login;

And this server side signin route and here request will come

    / var token;
router.post('/signin',async (req, res) => {
  try {
    // let token;
    const {email,password} = req.body;
    console.log(req.body);
    if(!email || !password) {
      return res.status(400).json({error:"pls filled the data"})
    }
    const userlogin= await User.findOne({email:email});
     if(userlogin)
     {
       const isMatch= await bcrypt.compare(password,userlogin.password);
     const  token=await userlogin.generateAuthToken();
      //  console.log(token);
          res.cookie('jwtoken',"raushan");

       if(!isMatch)
       {
         res.status(400).json({error:'invalid Credentials'});
       }
       else
       {
         res.json({message:"user signin Successfully"});
       }
     }
     else
     {
       res.status(400).json({error:'invalid Credentials'});
     }

  } catch (error) {
     console.log(error);
  }
})

1 Answers1

0

after login api getting success response then you have to store cookie viva Client side in react

function setCookie(name,value,days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days*24*60*60*1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + (value || "")  + expires + "; path=/";
}
function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}
function eraseCookie(name) {   
    document.cookie = name +'=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}

GET And SET data....

setCookie('ppkcookie','testcookie',7);

var x = getCookie('ppkcookie');
Shantanu Sharma
  • 666
  • 6
  • 21