req.cookies returns [Object: null prototype] {} even if the cookie is set

Viewed 4236

I try to store and read a cookie via cookie-parser. Setting the cookie is working fine. Its listed under the "Application"-Tab of the dev tools:

enter image description here

But if i try to read the cookie like this:

app.post("/authStatus", function(req,res){

    console.log(req.cookies)
    
})

It will give back an empty Object:

enter image description here

Here is the whole Backend File:

const   cookieParser          = require("cookie-parser"),
        express               = require("express"),
        mongoose              = require("mongoose"),
        bcrypt                = require("bcrypt"),
        Joi                   = require("joi"),
        cors                  = require("cors"),
        jwt                   = require("jsonwebtoken"),
        
        app                   = express()

        require("dotenv").config()
        
        app.use(cookieParser())
        app.use(express.urlencoded({extended: false}))
        app.use(cors({
            origin: "http://localhost:3000",
            credentials: true,
        }))

mongoose.connect(process.env.DB_CONNECTION, {
    useNewUrlParser: true, 
    useUnifiedTopology: true
},() => {
    console.log("Status: Mongoose: Connected (Test Database)")
})

//Models

const User          = require("./Models/UserModel")

//ValidationFunctions

const {registerValidation, loginValidation} = require("./Validation")
const VerifyToken = require("./VerifyToken")

//Search

app.post("/search", function(req,res,next){
    var keyword = req.body.keyword
    res.redirect("/search/"+ keyword)
})

app.get("/search/:keyword", function(req,res,next){

})

//Registration


app.post("/register", async (req,res) => {

    //Validation

    const {error} = registerValidation(req.body)

    if(error) return res.status(400).send(error.details[0].message)

    //Check if user is already in Database

    const emailExist = await User.findOne({email: req.body.email})

    if(emailExist) return res.status(400).send("")

    // Create User 
    try{
        
        const saltRounds = 10;

        var hashedPassword = await bcrypt.hash(req.body.password, saltRounds)

        const user = new User({
            firstname: req.body.firstname,
            lastname:req.body.lastname,
            gender:req.body.gender,
            birth:req.body.birth,
            street:req.body.street,
            streetnumber:req.body.streetnumber,
            location: req.body.location,
            email:req.body.email,
            password: hashedPassword,

        })

        user.save().then(result => {
            console.log(result)
            res.redirect("/registered")
        })
        
    }
    catch{
        res.status(400).send(err)
    }
})

//Login/Logout

app.post("/login", async (req, res) => {

    // Validation

    const {error} = loginValidation(req.body)
    if(error) return res.status(400).send(error.details[0].message)

    // Check if email exist in DB
    
    const user = await User.findOne({email: req.body.email})
    if(!user) return res.status(400).send("No user found")
    console.log(user)

    // Password is correct 
    const validPass = await bcrypt.compare(req.body.password, user.password)
    if(!validPass) return res.status(400).send("Wrong password")
    
    // Create and assign token
    const token = jwt.sign({_id: user._id}, process.env.TOKEN_SECRET)

    res.cookie("auth", token, {httpOnly: true, secure:false}).redirect("/main")
})

app.post("/authStatus", function(req,res){

    console.log(req.signedCookies)
    console.log(req.cookies)
    
})

app.post("/logout", (req, res) => {
    res.cookie("auth", 0, {maxAge:0}).redirect("/main")
})

function verifyToken(req,res,next){

    const token = req.cookies

    if(!token) return res.redirect("/loginFirst")

    try{    
        const user = jwt.verify(token, process.env.TOKEN_SECRET)
        req.user = user
    }

    catch{
        res.status(400).send("Invalid Token")
    }
}


app.listen(process.env.PORT, function(){
    console.log("Status: Express: Server running on PORT: " + process.env.PORT)
})

I hope you can help me with that, im quite stuck with it.

3 Answers

It seems like i solved the problem, nevertheless I cannot explain exactly why it works now. On the frontend i fired the request via Axios and typed "http://localhost:5000/authStatus" as the URL. I tried to just fire it with just "/authStatus" and added a proxy of "http://localhost:5000" in the frontend package.json. And now it works.

this error might be because you might be using '127.0.0.1' and also 'localhost'

use either "127.0.0.1" or "localhost" anyone only

try this

http://localhost:5000/login

http://localhost:5000/authStatus

http://localhost:5000/logout

Try to add: withCredentials: true, when you send the req to the backend

const handleSubmit = async (e) => {
    e.preventDefault();
    let formData = new FormData();
    formData.append("file", file);

    try {
        await axios.post('http://localhost:4000/add-book',
            {
                universityOption,
                collegeOption,
                subjectOption,
                emailOption,
                phoneNumberOption,
                file,
                postAs
            },
            {
                withCredentials: true,
                headers: { 'Content-Type': 'multipart/form-data' },
            })
            .then((res) => {
                console.log(res)
                setUniversityOption('')
                setCollegeOption('')
                setSubjectOption('')
                setEmailOption('')
                setPhoneNumbeOption('')
                setFile('')
                setPostAs([])
            })

    } catch (err) {
        console.log(err)
    }
}
Related