M
M
Markiv072022-03-17 00:25:59
Node.js
Markiv07, 2022-03-17 00:25:59

How to add cookies to browser storage?

Hello. The Login function (hereinafter referred to as "login") was written by me to authorize the user to the website, it was written in Node.js. I encountered such a problem: when authorizing through the Client side (Client side (front)) cookies (hereinafter referred to as cookies), are not added to the browser storage. I tested this function through the Postman application, which I use to test the API, everything works fine there, i.e. cookies are added and access to the part where login is required is available. During normal testing on localhost, nothing works, despite the fact that it does not give any errors. Please note that the last console.log("logged") is executed, i.e. "logged" is displayed in the console, I assume that the function still works. Please help me to solve this problem.
Here is a piece of code (for this Login function):

app.post("/login", async (req, res)=>{
    const {username, password} = req.body

    const userFind = "SELECT * FROM users WHERE username = ?"
    con.query(userFind, username, (err, result) =>{
        if(result.length === 0) {
            return res.status(400).json("User doesn't exist")
        }

        const dbPassword = result[0].password

        bcrypt.compare(password, dbPassword).then((match)=>{
            if(!match){
                return res.status(400).json({error: "Wrong username or password"})
            }else{
                const accessToken = createTokens(result[0])

                res.cookie("access-token", accessToken, {
                    maxAge: 60*60*24*30*1000,
                    httpOnly: true
                })

                res.json("Logged")
                console.log("logged")
            }
        })
    })
})


With best regards, Vladimir!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Markiv07, 2022-03-25
@Markiv07

I solved the problem, I just added withCredentials:true when I called it, everything worked

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question