简体   繁体   中英

How can i fix (node:5796) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: error?

I ran my node js app but then after signing up to my app then it gave me this error. What is it and how can i fix it.

(node:5796) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client at ServerResponse.setHeader (_http_outgoing.js:518:11) at ServerResponse.header (C:\Users\Children\Desktop\Web Projects\Sermon_Tracker\node_modules\express\lib\response.js:767:10) at ServerResponse.send (C:\Users\Children\Desktop\Web Projects\Sermon_Tracker\node_modules\express\lib\response.js:170:12) at ServerResponse.json (C:\Users\Children\Desktop\Web Projects\Sermon_Tracker\node_modules\express\lib\response.js:267:15) at C:\Users\Children\Desktop\Web Projects\Sermon_Tracker\app.js:171:9 at processTicksAndRejections (internal/process/task_queues.js:97:5) (node:5796) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with.catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode ). (rejection id: 1) (node:5796) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

I think i know where the error is looking at the error but i cant seem to fix it. This is my code:


app.post('/signup', async (req, res) => {

    // res.json({ status: "ok" });

    // const firstName = req.body.firstName;
    // const lastName = req.body.lastName;
    //const username = req.body.email;
    //const password = req.body.password;

    // user = email;

    // const User1 = mongoose.model("User", userSchema);

    // const user2 = new User1({
    //     first_name: firstName,
    //     last_name: lastName,
    //     email: email,
    //     password: password,
    // });

    // user2.save();

    // console.log(user + "Done");

    // res.redirect("/workspace");

    // Hashing passwords

    const { username, password: plainTextPassword } = req.body;

    userN = username;


    if (!username || typeof username !== 'string') {
        return res.json({ status: 'error', error: 'Invalid username' });
    }

    if (!plainTextPassword || typeof plainTextPassword !== 'string') {
        return res.json({ status: 'error', error: 'Invalid password' });
    }

    if (plainTextPassword.length < 5) {
        return res.json({ status: 'error', error: 'Password too small. Should be atleast 6 characters long.' });
    }

    const password = await bcrypt.hash(plainTextPassword, 10);

    try {
        const response = await User.create({
            _id: userN,
            username,
            password
        });
        console.log('user created successfully: ', response);
        res.redirect('/workspace');
    } catch (error) {
        if (error.code == 11000) {
            return res.json({ status: 'error', error: 'Username already taken' });
        }
        throw error
    }

    const item1 = new Item({
        _id: userN,
        date: "Date",
        loc: "Location",
        title: "Title",
        passage: "Passage",
        file: "File"
    });

    defaultItems.push(item1);

    res.json({ status: 'ok' });

});

Here is the rest of the code:

var userN;

var defaultItems = [];

mongoose.connect('mongodb://localhost:27017/sermontracker',
    {
        useNewUrlParser: true,
        useUnifiedTopology: true,
        useCreateIndex: true

    }
);

const ItemSchema = new mongoose.Schema({
    _id: String,
    date: String,
    loc: String,
    title: String,
    passage: String,
    file: String
});

const Item = mongoose.model("Item", ItemSchema);


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

  
    const { username, password } = req.body;

    const user = await User.findOne({ username }).lean();

    userN = username;


    if (!user) {
        return res.json({ status: 'error', error: 'Invalid username/password' })
    }

    if (await bcrypt.compare(password, user.password)) {

        const token = jwt.sign({ id: user._id, username: user.username }, JWT_SECRET);

        res.redirect('/workspace');

        res.json({ status: 'ok', data: token });

    }

    res.json({ status: 'ok', error: 'Invalid user/password' });


});

app.post('/signup', async (req, res) => {

   
    const { username, password: plainTextPassword } = req.body;

    userN = username;


    if (!username || typeof username !== 'string') {
        return res.json({ status: 'error', error: 'Invalid username' });
    }

    if (!plainTextPassword || typeof plainTextPassword !== 'string') {
        return res.json({ status: 'error', error: 'Invalid password' });
    }

    if (plainTextPassword.length < 5) {
        return res.json({ status: 'error', error: 'Password too small. Should be atleast 6 characters long.' });
    }

    const password = await bcrypt.hash(plainTextPassword, 10);

    try {
        const response = await User.create({
            _id: userN,
            username,
            password
        });
        console.log('user created succecfully: ', response);
        res.redirect('/workspace');
    } catch (error) {
        if (error.code == 11000) {
            return res.json({ status: 'error', error: 'Username already taken' });
        }
        throw error
    }

    res.json({ status: 'ok' });

    const item1 = new Item({
        _id: userN,
        date: "Date",
        loc: "Location",
        title: "Title",
        passage: "Passage",
        file: "File"
    });

    defaultItems.push(item1);

});

app.get("/", function (req, res) {

    res.render("home");

});

app.get("/change-password", function (req, res) {

    res.render("changepass");

});

app.get("/signup", function (req, res) {

    res.render("signup");

});

app.get("/login", function (req, res) {

    res.render("login");

});

app.get("/workspace", function (req, res) {

    Item.find({ _id: userN }, function (err, foundItems) {

        if (foundItems.length == 0) {
            Item.insertMany(defaultItems, function (err) {
                if (err) {
                    console.log(err);
                } else {
                    console.log("Added items");
                }
            });
            res.redirect("/workspace");

        } else {
            res.render("workspace", { itemList: foundItems });
        }
    });


});


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

    const date = req.body.input1;
    const location = req.body.input2;
    const title = req.body.input3;
    const passage = req.body.input4;
    const file = req.body.input5;

    const item = new Item({
        _id: userN,
        date: date,
        loc: location,
        title: title,
        passage: passage,
        file: file
    });

    item.save();

    res.redirect("/workspace");
});

First of all, it does not seem like userN is a variable. (But no error is thrown, so..) You are redirecting, and then returning some JSON. That is why the error is thrown. Try returning JSON before redirecting. (if you need to). The error explains this (in some cryptic way:) )

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