首页 > 解决方案 > Does the route of a .post() method matter?

问题描述

I get the same behavior with all of the following code examples even though they have different routes in the .post() method. Is there a case where the route would matter?

Example 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">

Example 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">

标签: expresspostejs

解决方案


The resource you're sending your POST request to would matter in most APIs, particularly REST APIs. What difference it makes is up to your particular API specification.

The resource generally specifies what type of resource you're trying to manipulate, so if you send a POST request to "/users", you're trying to create/update a user. If you send a request to e.g. "/products", you're trying to create/update a product. Business logic and validation rules would be different for the different resources.

Inside your specific API you're probably free to do whatever you like, you can create an endpoint with the resource name "/unicorns" that returns pictures of airplanes, but your intention will not be very clear to other developers. If you handle different types of resources, you probably want to register them to different resource endpoints in order to encode the intention of the request.


推荐阅读