简体   繁体   中英

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

I am new to node.js and I am working in the client-side with a regular js and I got this error:

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

my server code is:

app.get('/connect', function (req, res) {
    console.log("connect to the user");
    res.sendFile(path.join(__dirname, 'client', 'connect.html'));
});

app.post('/connect', function (req, res) {
    const userNameEnter = req.body.userName;
    const passwordEnter = req.body.password;

// //entering if the user and pass are correct
if (userNameEnter !== undefined && passwordEnter !== undefined) {
    User.findOne({ userName: userNameEnter }, function (err, user) {
        console.log(err);
        if (user !== null) { //can enter
            if (user.userPassword === passwordEnter) {
                res.json({
                    status: "seccess",
                    user: "canEnter"
                });
                console.log("can enter");
                res.redirect("/gameManage/" + user.id);
            } else {//cant enter
                res.json({
                    status: "seccess",
                    user: "notOk"
                });
            }
        } else {//cant enter
            res.json({
                status: "seccess",
                user: "notOk"
            });
            console.log("cant enter");
        }
    });
}
console.log(newUser);

});

I have to send the JSON because the js needs to know what to do next. How can I redirect it in another way so I do have the parameter of the userId in the URL line?

You can't send response to the client and then also redirect the client. You should send the redirect path to the client and then redirect from client side using javascript

res.json({
     status: "seccess",
     user: "canEnter",
     redirectPath: "/gameManage/" + user.id
});

On client side

if (response.redirectPath) {
    window.location.href = response.redirectPath;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM