.post() 方法的路由重要吗?
Does the route of a .post() method matter?
尽管以下所有代码示例在 .post() 方法中具有不同的路由,但我得到了相同的行为。是否存在路线重要的情况?
示例 1:
index.js
app.post("/", async (req, res) => {
const newProduct = new Product(req.body);
await newProduct.save();
res.redirect(`/products/${newProduct._id}`);
});
index.ejs
<form action="/" method="post">
示例 2:
index.js
app.post("/products", async (req, res) => {
const newProduct = new Product(req.body);
await newProduct.save();
res.redirect(`/products/${newProduct._id}`);
});
index.ejs
<form action="/products" method="post">
您发送 POST 请求的资源在大多数 API 中都很重要,尤其是 REST API。它有什么不同取决于您的特定 API 规范。
资源通常会指定您要操作的资源类型,因此如果您向“/users”发送 POST 请求,您就是在尝试 create/update 一个用户。如果您向例如“/products”,您正在尝试 create/update 一种产品。不同资源的业务逻辑和验证规则会有所不同。
在您的特定 API 中,您可能可以自由地做任何您想做的事情,您可以创建一个资源名称为“/unicorns”的端点,其中 returns 飞机的图片,但您的意图其他开发者不会很清楚。如果您处理不同类型的资源,您可能希望将它们注册到不同的资源端点,以便对请求的意图进行编码。
尽管以下所有代码示例在 .post() 方法中具有不同的路由,但我得到了相同的行为。是否存在路线重要的情况?
示例 1:
index.js
app.post("/", async (req, res) => {
const newProduct = new Product(req.body);
await newProduct.save();
res.redirect(`/products/${newProduct._id}`);
});
index.ejs
<form action="/" method="post">
示例 2:
index.js
app.post("/products", async (req, res) => {
const newProduct = new Product(req.body);
await newProduct.save();
res.redirect(`/products/${newProduct._id}`);
});
index.ejs
<form action="/products" method="post">
您发送 POST 请求的资源在大多数 API 中都很重要,尤其是 REST API。它有什么不同取决于您的特定 API 规范。
资源通常会指定您要操作的资源类型,因此如果您向“/users”发送 POST 请求,您就是在尝试 create/update 一个用户。如果您向例如“/products”,您正在尝试 create/update 一种产品。不同资源的业务逻辑和验证规则会有所不同。
在您的特定 API 中,您可能可以自由地做任何您想做的事情,您可以创建一个资源名称为“/unicorns”的端点,其中 returns 飞机的图片,但您的意图其他开发者不会很清楚。如果您处理不同类型的资源,您可能希望将它们注册到不同的资源端点,以便对请求的意图进行编码。