Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/email/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何修复(节点:5796)未处理的PromisejectionWarning:Error[ERR\u HTTP\u HEADERS\u SENT]:Error?_Javascript_Html_Node.js_Mongodb_Mongoose - Fatal编程技术网

Javascript 如何修复(节点:5796)未处理的PromisejectionWarning:Error[ERR\u HTTP\u HEADERS\u SENT]:Error?

Javascript 如何修复(节点:5796)未处理的PromisejectionWarning:Error[ERR\u HTTP\u HEADERS\u SENT]:Error?,javascript,html,node.js,mongodb,mongoose,Javascript,Html,Node.js,Mongodb,Mongoose,我运行了我的NodeJS应用程序,但在注册我的应用程序后,它给了我这个错误。它是什么?我如何修复它 (节点:5796)未经处理的PromisejectionWarning:错误[ERR_HTTP_HEADERS_SENT]:将头发送到ServerResponse.setHeader(_HTTP_outgoing.js:518:11)的客户端之后,无法设置头(C:\Users\Children\Desktop\Web Projects\Sermon\u Tracker\node\modules\e

我运行了我的NodeJS应用程序,但在注册我的应用程序后,它给了我这个错误。它是什么?我如何修复它

(节点:5796)未经处理的PromisejectionWarning:错误[ERR_HTTP_HEADERS_SENT]:将头发送到ServerResponse.setHeader(_HTTP_outgoing.js:518:11)的客户端之后,无法设置头(C:\Users\Children\Desktop\Web Projects\Sermon\u Tracker\node\modules\express\lib\response.js:767:10)位于ServerResponse.send(C:\Users\Children\Desktop\Web Projects\Sermon\u Tracker\node\u modules\express\lib\response.js:170:12)在ServerResponse.json(C:\Users\Children\Desktop\Web Projects\Sermon\u Tracker\node\u modules\express\lib\response.js:267:15)在C:\Users\Children\Desktop\Web Projects\Sermon\u Tracker\app.js:171:9的ProcessTicks和Rejections(internal/process/task\u queues.js:97:5)(节点:5796)UnhandledPromisejectionWarning:Unhandled Promisejection拒绝。此错误源于在没有catch块的异步函数内部抛出,或拒绝未使用.catch()处理的承诺。若要在未处理的承诺拒绝时终止节点进程,请使用CLI标志
--Unhandled rejections=strict
(请参阅)。(拒绝id:1)(节点:5796)[DEP0018]弃用警告:未处理的承诺拒绝已弃用。将来,未处理的承诺拒绝将使用非零退出代码终止node.js进程

我想我知道错误在哪里,但我似乎无法修复它。这是我的代码:


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' });

});

app.post('/signup',异步(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;
//用户=电子邮件;
//const User1=mongoose.model(“用户”,userSchema);
//const user2=new User1({
//名字:名字,
//姓氏:姓氏,
//电邮:电邮,,
//密码:密码,
// });
//user2.save();
//console.log(用户+“完成”);
//res.redirect(“/workspace”);
//散列密码
const{username,password:plainTextPassword}=req.body;
userN=用户名;
如果(!username | | typeof username!=“string”){
返回res.json({status:'error',error:'Invalid username'});
}
如果(!plainTextPassword | | plainTextPassword的类型!=='string'){
返回res.json({status:'error',error:'Invalid password'});
}
如果(明文密码长度<5){
返回res.json({status:'error',error:'密码太小。长度至少应为6个字符。');
}
const password=wait bcrypt.hash(明文密码,10);
试一试{
const response=wait User.create({
_id:userN,
用户名,
密码
});
log('user created successfully:',response);
res.redirect('/workspace');
}捕获(错误){
如果(错误代码==11000){
返回res.json({status:'error',error:'Username ready take'});
}
抛出错误
}
const item1=新项目({
_id:userN,
日期:“日期”,
loc:“位置”,
标题:“标题”,
段落:“段落”,
文件:“文件”
});
defaultItems.push(item1);
res.json({status:'ok'});
});
以下是代码的其余部分:

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");
});

var-userN;
var defaultItems=[];
猫鼬mongodb://localhost:27017/sermontracker',
{
useNewUrlParser:true,
useUnifiedTopology:正确,
useCreateIndex:true
}
);
const ItemSchema=new mongoose.Schema({
_id:String,
日期:String,
loc:字符串,
标题:字符串,
短文:弦,
文件:字符串
});
const Item=mongoose.model(“Item”,ItemSchema);
app.post(“/login”),异步(请求、回复)=>{
const{username,password}=req.body;
const user=wait user.findOne({username}).lean();
userN=用户名;
如果(!用户){
返回res.json({status:'error',error:'Invalid username/password'})
}
if(等待bcrypt.compare(密码、用户密码)){
const-token=jwt.sign({id:user.\u-id,username:user.username},jwt\u-SECRET);
res.redirect('/workspace');
res.json({status:'ok',data:token});
}
res.json({status:'ok',error:'Invalid user/password'});
});
app.post('/signup',异步(req,res)=>{
const{username,password:plainTextPassword}=req.body;
userN=用户名;
如果(!username | | typeof username!=“string”){
返回res.json({status:'error',error:'Invalid username'});
}
如果(!plainTextPassword | | plainTextPassword的类型!=='string'){
返回res.json({status:'error',error:'Invalid password'});
}
如果(明文密码长度<5){
返回res.json({status:'error',error:'密码太小。长度至少应为6个字符。');
}
const password=wait bcrypt.hash(明文密码,10);
试一试{
const response=wait User.create({
_id:userN,
用户名,
密码
});
log('user created successfully:',response);
res.redirect('/workspace');
}捕获(错误){
如果(错误代码==11000){
返回res.json({status:'error',error:'Username ready take'});
}
抛出错误
}
res.json({状态:'ok'