0

i am trying to set a cookie if a person enters the correct key (1234) but when they type in the correct key it spits out an error

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

idk what to do i tried to redirect before setting the cookie and even just logging after the redirect but the error doesn't go away!

heres my code: key is defined just not in this part

app.get("/", function(req,res) {
    if (req.cookies.userSecret == key) {
    res.sendFile(__dirname + "/index.html");
    } else {
        res.sendFile(__dirname + "/login.html")
        io.on("connection", function(socket) {
            socket.on("login", function(data){
                if (data == key) {
                    res.redirect("/1799fd8e-78aa-4bc0-9692-011a81c07248")
                    return false;
                } else {
                    io.emit("log", "Wrong key! try again")
                    return false;
                }
            })
        })
    }
});

app.get("/1799fd8e-78aa-4bc0-9692-011a81c07248", function(req,res) {
    console.log(key)
    res.sendFile(__dirname + "/index.html")
})
  • 1
    What are you trying to do? You're using `res.redirect()` after the response was already sent in your `socket.on('login')`. – mbrandau Feb 19 '18 at 10:34
  • im trying to confirm if the user has the key and if so they will be redirected EDIT: I was trying to run res.cookie but it gave me the same error so i tried redirect to res.cookie but still no result – SpoodytheOne Feb 19 '18 at 10:36
  • As it says, you cannot sent headers after they've already been sent. This is a different language, but a good explanation of the issue: https://stackoverflow.com/a/8028987/476 – deceze Feb 19 '18 at 10:41

1 Answers1

2

You cannot redirect a user after the request was already sent. You'll have to redirect the user from the client side. Like you're doing it in the else part, you would emit an event to the user containing the URL to redirect to and on the client side receive this event and change the URL with window.location.

mbrandau
  • 544
  • 3
  • 14