【问题标题】:How to prevent user from accessing route directly in express?如何防止用户直接在 express 中访问路由?
【发布时间】:2021-10-08 14:45:51
【问题描述】:

我正在开发一个网络应用程序,用户可以在其中填写他们的联系方式并提交表单。提交后,我将它们重定向到/failure/success where

app.get("/success", function(req, res) {
    res.sendFile(__dirname + "/success.html");
});

app.get("/failure", function(req, res) {
    res.sendFile(__dirname + "/failure.html");
});

但是,用户也可以访问/failure/success,如果他们只需在url 的路径中输入这些。我怎样才能防止这种情况?我只希望在提交表单后显示失败/成功页面。

【问题讨论】:

  • 在标题或帖子正文中设置一些内容(作为隐藏参数)并在两条路线中读取它,即/success & /failure

标签: node.js express web-applications


【解决方案1】:

使用条件语句,例如用户输入的消息是否插入重定向到路由成功或返回失败。 例子。 如果数据插入成功 重定向('/成功') 别的 重定向('/失败')

【讨论】:

    【解决方案2】:

    在标题或您的帖子正文中设置一些内容(作为表单中的隐藏参数)并在您的两条路线中读取它,即/success & /failure

    例子

    表格

    <form action="<action>" method="POST" enctype='multipart/form-data'>
        <!-- this is your validation field -->
        <!-- (redirect this value onto your success or failure routes as a query param) -->
        <input type="hidden" name="validation" value="true" />
    
        ...
        <!-- continue with your form -->
    </form>
    

    然后在你的路线中:

    app.get("/success", function(req, res) {
        if (req.query.validation == true)
            res.sendFile(__dirname + "/success.html");
        else
            res.json({ error: 403, message: "Forbidden" });
    });
    
    // same goes for /failure 
    

    【讨论】:

      猜你喜欢
      • 2021-08-29
      • 2021-10-05
      • 1970-01-01
      • 2015-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多