0

I am using Cookie - Parser with express.js. In my express config file I have app.use(cookieParser()) and in my main (app.js) for the server I set the cookie whenever there is a POST request to /signIn and username and password are both equal.

app.post("/signIn",(req,res)=>{
    log(`Checking .....`);
    const req_data=req.body;
    log(req.body);
    if(req.body.user===req.body.password) {
        res.cookie.level="recruiter";//I even tried doing with res.cookie("level","recruiter")
        res.send({redirect:true,redirect_url:"\\"+res.cookie.level})
    } else {
        log(`Fishy..!`);
        res.send({"authenticated":false});
    }
});

Now when the client receives this as a part of the Fetch API response it extracts the redirect_url part of the JSON and do something like below:

fetch("/signIn",{
    method:"POST",
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    },
    body:JSON.stringify(json)
})
.then((res)=>{
    log(res);
    return res.json();
})
.then((res)=>{
    if(res["authenticated"] == false) {
        $("#credential_alert").style="display:block;";
        setTimeout(function(){
            $("#credential_alert").style="display:none;";
        },1000);
        $("#user").value="";
        $("#password").value="";
    } else if(res["redirect"]===true && res["redirect_url"]) {
        window.location.href=res["redirect_url"];
    }
})

Now real issue is when in another route I am trying to access a HTTP cookie previously set in the /signIn route using below code..

app.get("/recruiter",(req,res)=>{
    log(req.cookies.level);//Coming out as undefined
    res.render("recruiter.ejs");
});

As you can see, level from res.cookies is coming out as undefined I don't know why.

Answer Got the answer, actually fetch API does not send any credentials by default with it's request so we have to set credentials:true to send credentials along with fetch api's call.

Tarun Garg
  • 126
  • 8

1 Answers1

0

Hi Actually You're setting cookie only for that request means(by defualt httpOnly :true) So you've to set cookie like this res.cookie("level","recruiter",{httpOnly:false,maxAge:/optional/})

Sunil More
  • 208
  • 2
  • 6