如何读取从HTML表单发送到Node.js的POST请求的响应?

时间:2018-07-24 10:32:57

标签: html node.js

我正在填写“创建帐户”表格。用户提交后,服务器将确保字段不为空且未使用用户名(文档存储在MongoDB中)。如果有错误,我想将错误传回给我。

以下HTML:

    <form action="/createaccount" id="myform" method="POST">

    <label>Enter your first name</label>
    <input type="text" placeholder="First name" name="firstname">

    </br><label>Enter your last name</label>
    <input type="text" placeholder="Last name" name="lastname">

    </br><label for="uname">Enter a username</label>
    <input type="text" placeholder="Username" name="username">

    </br><label for="psw">Enter a password</label>
    <input type="password" placeholder="Password" name="password">

    </br><button type="submit">Create Account</button>
    <div id="error"></div>


</form>

下面的Node.js服务器:

app.post('/createaccount', (req, res) => {
    new_username = req.body.username;
    new_password = req.body.password;
    new_firstname = req.body.firstname;
    new_lastname = req.body.lastname;

    MongoClient.connect(url, (err, client) => {
        if (err) return console.log(err)
        db = client.db('entelligence')

        var myobj = {
            firstName: new_firstname,
            lastName: new_lastname,
            username: new_username,
            password: new_password
        };

        var match = false;
        var empty = false;
        var error_string = "";
        for (var i = 0; i < array.length; i++) {
            console.log(array[i].username);
            if (array[i].username == new_username) {
                match = true;
            }
        }

        if (match) {
            error_string = "Username is  already taken. "
        };
        if (new_firstname == '' || new_lastname == '' || new_username == '' || new_password == '') {
            error_string += "Field(s) cannot be empty";
        }
        console.log(error_string);

        if (error_string == "") {
            db.collection("users").insertOne(myobj, function(err, res) {
                if (err) throw err;
                console.log("1 document inserted");
            });
            res.redirect('/');
        }

        res.send(error_string);

    })
})

当我按下创建帐户时,出现“发送后无法设置标题”错误,但是我找不到在1个请求中发送多于1个响应的位置。另外,如果我输入有误(例如,将字段留空),我会被定向到/ createaccount,在此我会得到带有正确错误的文本。如果发生错误,我不想加载任何页面。我只希望表单页面上显示错误。任何人都知道如何做吗?

1 个答案:

答案 0 :(得分:1)

这与在响应上设置响应头有关。 This answer has some good explanations,了解发生这种情况的原因。

当您多次调用snapshot_idres.send时,通常会发生这种情况,请尝试将它们返回以防止这种情况发生:

res.redirect