使用 Express(和 MySQL)应该在哪里进行数据验证?

发布于 2025-01-10 13:56:24 字数 1593 浏览 0 评论 0原文

我目前正在通过使用 Express 创建 REST API 来学习 MySQL。我选择验证服务器上的数据而不是数据库上的数据。我的问题是,我应该在服务器上的哪里执行此操作? 我应该验证数据(例如用户名的最小和最大长度)...

  • ...在控制器文件之前使用中间件吗?
  • ...在控制器文件中,在收到请求之后并将数据发送到模型文件之前? (下面的示例文件)
  • ...查询之前的模型文件? (下面的示例文件)
  • ...一些我没有想到的完全其他的解决方案?

./controllers/authController.js

const register = async (req, res) => {
  const { username, email, password } = req.body;

    **// Validating input data here?**

  // TODO hash password
  const activationToken = generateActivationToken(48);
  const newUser = await User.create(
    { username, email, password, activationToken },
    (err, result) => {
      console.log(err);
      if (err)
        return res.status(400).json({
          msg: err.message || "Some error has occured. Please try again.",
        });
      else res.json({ result });
    }
  );
};

./models/User.js

var db = require("../dbconnection");

// constructor for User object
const User = function (user) {
  this.username = user.username;
  this.email = user.email;
  this.password = user.password;
  this.activationToken = user.activationToken;
};

User.create = (newUser, result) => {

**// Validating input data here?**

  db.query("INSERT INTO users SET ?", newUser, (err, res) => {
    if (err) return result(err, null);

    console.log("Created user.");
    result(null, { id: res.insertId });
  });
};

module.exports = User;

执行此操作的通常/最佳实践方法是什么?如果没有最佳实践,您该如何做? (当然,我也在前端验证数据。)您知道我可以看一下什么好的示例项目吗?

谢谢您的宝贵时间!

I'm currently learning MySQL by creating an REST API using Express. I've opted for validating data on the server instead of the database. My question is, WHERE on the server should I do that?
Should I validate data (for example minimum and maximum length for the username)...

  • ...using a middleware before the controller file?
  • ...in the controller file, after reciving the request and before sending the data to the models file? (example file below)
  • ...the models file before querying? (example file below)
  • ...some completely other solution I haven't thought of?

./controllers/authController.js

const register = async (req, res) => {
  const { username, email, password } = req.body;

    **// Validating input data here?**

  // TODO hash password
  const activationToken = generateActivationToken(48);
  const newUser = await User.create(
    { username, email, password, activationToken },
    (err, result) => {
      console.log(err);
      if (err)
        return res.status(400).json({
          msg: err.message || "Some error has occured. Please try again.",
        });
      else res.json({ result });
    }
  );
};

./models/User.js

var db = require("../dbconnection");

// constructor for User object
const User = function (user) {
  this.username = user.username;
  this.email = user.email;
  this.password = user.password;
  this.activationToken = user.activationToken;
};

User.create = (newUser, result) => {

**// Validating input data here?**

  db.query("INSERT INTO users SET ?", newUser, (err, res) => {
    if (err) return result(err, null);

    console.log("Created user.");
    result(null, { id: res.insertId });
  });
};

module.exports = User;

What's the usual/best practice way of doing this? If there isn't a best practice, how do YOU do it? (I validate data on the front-end too of course.) Do you know of any good example projects I could take a look at?

Thank you for your time!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

勿忘初心 2025-01-17 13:56:24

在 OOP 中有一个原则称为:

信息专家原则

根据这个原则,我们应该在包含最多信息的对象内分配职责/方法来完成任务
(它帮助我们创建有凝聚力的班级)。

因此,您可能应该将验证逻辑放入用户模型中

In OOP there's a principle called as:

"The information Expert principle"

According to this principle we should assign responsibilities / methods inside the objects that contain the most information to fulfil the task
(It helps us create cohesive classes).

So, you should probably put the validation logic inside the User model.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文