使用 express 进行表单验证

Form validation with express

我了解到客户端的表单验证不足以防止用户的任何恶意操作。对于那种情况,我已经阅读过验证服务器端表单所需的内容。由于我是第一次使用快递,有人可以告诉我我需要做什么吗?

我将 html 表单和 js 验证函数留在这里。我的表单没有用于测试目的的“操作”和“方法”。我知道“操作”会导致我的验证页面,并且在这种特定情况下方法是 POST。

为验证创建一个模块然后在 server.js 上调用它是否更安全?或者我可以在 server.js?

中编码吗

HTML

     <div class="containerfrm" id="frmcntn">
     <!--Form Creation with method POST, JavaScript input validations and php file validation-->
     <form action="" method="" class="cntbox" id="formBoard" name="formOfBoard" onsubmit="validateIndexForm(event)">
     <!--Close Button of the pop up-->
                    <div class="righttopicon" onclick="closeForm()">
                        <img src="images/square-x.png" alt="close icon">
                    </div>

                    <!--Form with the necessary inputs (Name of the Board, IP Address, Port and upload file). All the inputs are required-->
                    <div class="col-100">
                        <h3>Add new board:</h3>
                    </div>
                    <!--Input for the boards name with max length of 50 characters-->
                            <div class="col-75">
                                <label for="bname">Name of the Board: *</label><br>
                                <input type="text" id="boardname" name="boardname" placeholder="Ex: Board 1" maxlength="50">
                            </div>
                            <!--Input for the IP Address that can only accept IP's and with a max length of 15 characters-->
                            <div class="row">
                                <div class="col-75">
                                    <label for="ipadd">IP Address: *</label><br>
                                    <input type="text" name="ipadd" id="ipaddress" placeholder="Ex: 192.168.1.1" maxlength="15">
                                </div>
                            </div>
                            <!--Input for the Port that can only accept numbers with a max length of 4-->
                            <div class="row">
                                <div class="col-75">
                                    <label for="portnum">Port: *</label><br>
                                    <input type="text" name="portnum" id="portnum" placeholder="Ex: 8080" maxlength="4" minlength="2">
                                </div>
                            </div>
                            <!--Input for the upload of the boards image that can only accept .png files-->
                            <div class="row">
                                <div class="col-75">
                                    <label for="imgadd">Upload image:</label><br>
                                    <img src="images/file-upload.png" alt="Insert image" class="insrtimg" name="imageboard" id="insertimage">
                                    <input type="file" id="myFile" name="filename" onchange="fileValidation(event)">
                                </div>
                            </div>
                            <!--'Save' and 'Discard' buttons -->
                            <div class="row">
                                <div class="col-80">
                                    <div class="btnformcontainer">
                                        <input type="submit" class="btnfrm btnconfrm" value="Save">
                                        <div class="btnfrm btndel"  onclick="discardValues()">Discard</div>
                                    </div>
                                </div>
                            </div>
                    </form>
                </div>

JS 验证

function validateIndexForm(event){
    let x = document.getElementById("boardname").value;
    let y = document.getElementById("ipaddress").value;
    let z = document.getElementById("portnum").value;
    let w = document.getElementById("myFile").value;

    let ipformat = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;;
    
    if(x == ""){
        //prevent the form submit
        event.preventDefault();
        alert("Please insert the boards name");
        return false;
    }
    if(!y.match(ipformat) && !y === "localhost"){
        //prevent the form submit
        event.preventDefault();
        alert("Please insert a valid IP address");
        return false;
    }
    if(z != isNaN() && !(z > 0)){
        //prevent the form submit
        event.preventDefault();
        alert("Please insert the correct port");
        return false;
    }
    if(w == ""){
       event.preventDefault();
        alert("Please insert a valid image");
        return false;
    }
    return x, y, z, w;
}

上传的文件正在其他函数上成功验证。

您可以在服务器端的 post 请求代码中做同样的事情。

例如:

app.post('/register', (req, res) => {
  let username = req.body.username;
  let password = crypto.createHash('sha256').update(req.body.password).digest('base64');
  let repassword = crypto.createHash('sha256').update(req.body.repassword).digest('base64');
if(password != repassword) return res.redirect('/login');
});

您也可以像这样在重定向中进行查询:

res.redirect('/login/?e=4&t=l');

并在客户端解析它们以显示密码不匹配等错误。

无论您是为验证创建一个模块并将其放入您的服务器文件还是将逻辑直接编码到您的服务器文件中,它都不会影响安全性并且产生相同的效果行为。

为了保护您的 server-side 表单验证,我建议将 express-validator 之类的工具与 body-parser.

结合使用

查看此 article 以获得上述设置的 hands-on 方法。