简体   繁体   English

我该如何修复(节点:5796)UnhandledPromiseRejectionWarning:错误[ERR_HTTP_HEADERS_SENT]:错误?

[英]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.我运行了我的节点 js 应用程序,但是在注册我的应用程序之后,它给了我这个错误。 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. (节点:5796)UnhandledPromiseRejectionWarning:错误 [ERR_HTTP_HEADERS_SENT]:在 ServerResponse.header(C:\Users\Children\Desktop\Web Projects\Sermon_Tracker\node_modules\express\lib\response.js:767:10) 在 ServerResponse.send (C:\Users\Children\Desktop\Web Projects\Sermon_Tracker\node_modules\express\lib\response.js:170:12 ) 在 ServerResponse.json (C:\Users\Children\Desktop\Web Projects\Sermon_Tracker\node_modules\express\lib\response.js:267:15) 在 C:\Users\Children\Desktop\app .js:171:9 at processTicksAndRejections (internal/process/task_queues.js:97:5) (node:5796) UnhandledPromiseRejectionWarning: 未处理的 promise 拒绝。 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().此错误源于在没有 catch 块的情况下抛出异步 function 内部,或拒绝未使用.catch() 处理的 promise。 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 ).要终止未处理的 promise 拒绝的节点进程,请使用 CLI 标志--unhandled-rejections=strict (请参阅https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode )。 (rejection id: 1) (node:5796) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. (拒绝 id:1)(节点:5796)[DEP0018] DeprecationWarning:不推荐使用未处理的 promise 拒绝。 In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.将来,未处理的 promise 拒绝将使用非零退出代码终止 Node.js 进程。

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:这是代码的rest:

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.首先, userN似乎不是一个变量。 (But no error is thrown, so..) You are redirecting, and then returning some JSON. (但没有抛出错误,所以..)您正在重定向,然后返回一些 JSON。 That is why the error is thrown.这就是引发错误的原因。 Try returning JSON before redirecting.在重定向之前尝试返回 JSON。 (if you need to). (如果你需要)。 The error explains this (in some cryptic way:) )该错误解释了这一点(以某种神秘的方式:))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 (节点:45207)UnhandledPromiseRejectionWarning:错误 [ERR_HTTP_HEADERS_SENT] - (node:45207) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT] (节点:23)UnhandledPromiseRejectionWarning:错误[ERR_HTTP_HEADERS_SENT]:将标头发送到客户端后无法设置标头 - (node:23) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client UnhandledPromiseRejectionWarning:错误 [ERR_HTTP_HEADERS_SENT]:在将标头发送到客户端后无法设置标头 - UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the clien 如何修复“错误 [ERR_HTTP_HEADERS_SENT]:将标头发送到客户端后无法设置标头” - how to fix "Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client" 如何修复 err_http_headers_sent - How to fix err_http_headers_sent node.js收到“ ERR_HTTP_HEADERS_SENT”错误 - node.js getting 'ERR_HTTP_HEADERS_SENT' error UnhandledPromiseRejectionWarning: 错误 [ERR_HTTP_HEADERS_SENT] - setInterval &amp; Axios.post 错误处理 - UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT] - setInterval & Axios.post error handling 异步代码设计错误。 UnhandledPromiseRejectionWarning:错误 [ERR_HTTP_HEADERS_SENT], - Error with async code design. UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT], ERR_HTTP_HEADERS_SENT 错误但找不到它的来源 - ERR_HTTP_HEADERS_SENT Error But Can't Find The Origin of it 节点JS:错误[ERR_HTTP_HEADERS_SENT]:发送到客户端后无法设置标头 - Node JS : Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM