Pratik Vyavahare
Pratik Vyavahare

Reputation: 61

cookie are not set in browser when I am use the node as backend

Cookies are not set in browser. I am use the node as backend. I am try to search problem some person tell that's cookies will not setting because of I am using react as front and node as backed both are run on same virtual server that is localhost. That why it happen. this is my code please help. User.js

const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const RegisterModel = require("../Model/RegisterModel")
const signIn = async (req,res)=>{
    try {
       const data = await RegisterModel.findOne({Email:req.body.email})
       const passwordMatch = await bcrypt.compare(req.body.password,data.Password)
       const token = await jwt.sign({Email : data.Email}, process.env.SECRET)
       
       if(!data) return res.status(404).json({islogin:false, message: "User doesn't exist" })
       if(!passwordMatch) return res.status(400).json({islogin:false,message: "Incorrect Password"})
       
       if(passwordMatch){
        res.cookie('newToken',token, { maxAge: 900000, httpOnly: false});
        res.status(200).send({id:data._id,email:data.Email,name:data.Name,islogin:true,token:token})
        
         }
    } catch (error) {
        res.status(404).json({islogin:false,message:"User doesn't exist"})
        console.log(error)
    }
}


module.exports = {signIn,signUp};

app.js

const express = require('express');

var cookieParser = require('cookie-parser')
const app = express();
app.use(cookieParser())
const dotenv = require('dotenv');
dotenv.config()

var cors = require('cors')
const PORT = process.env.PORT ;
const router = require("./Router/Router")

app.use(cors())
app.use(express.json())
app.use(express.urlencoded({extended:false}));
app.use(router);
require("./Connection/Connection")


app.listen(PORT,()=>{
        console.log(`Listen at Port ${PORT}` )
})

Upvotes: 0

Views: 916

Answers (3)

M.Murtaza Khanzada
M.Murtaza Khanzada

Reputation: 1

fetch('http://yourserver.com/api/route', { method: 'GET', credentials: 'include' // or 'same-origin' depending on your use case }) put the credential part in your client side when fetching and in server side put app.use(

cors({
    origin:"http://localhost:3000",
    credentials:true,
   
})

);

and cookies put

res.cookie('jwt',token,{
    maxAge:15*24*60*60*1000,
    httpOnly:true,
    sameSite: 'None',
    secure: true 
   
});

hope this helps.

Upvotes: 0

Zain Waseem
Zain Waseem

Reputation: 27

if you are using MERN React Node also if you are using Axios Add the below line on the top level of react application(e.g App.js)

axios.withCredentials = true

**on the backend

install cors

& add the below lines**

import cors from "cors";
import cookieParser from "cookie-parser";
app.use(cookieParser());
app.use(express.json());
app.use(cors({ credentials: true }));

Upvotes: 0

hydraCode
hydraCode

Reputation: 112

for set credentials data into browser it is necessary to run both side on same domain backend should be run on localhost or 127.0.0.1 and frontend should be run on localhost or 127.0.0.1 respectively. or

backend and frontend run on =localhost or

backend and frontend run on =127.0.0.1

if you are not sure then issue error's show on console. here

enter image description here

browser suggest you error regarding cookies.

also set cors policy on backend side like =

cors({origin:"http:localhost:frontendPORT", credentials:true})

frontend side on http request, must be set with credentials= true

this method work for me after spending 4 days.

Upvotes: 2

Related Questions