如何处理末尾有可选 's' 字符的路由

How to handle routes that have an optional 's' character at the end

在我的后端 REST API 我有处理产品的路线

[GET] /products
[GET] /product/:id
[POST] /product/:id

我想在 1 个路由器中处理它们(因为所有这些路径都适用于产品),但问题是我不知道如何区分 /products/product。我尝试使用像 /product+[s]? 这样的正则表达式,但是 /products/:id 也变成了一个有效路径,应该是无效的。

如何在同一个路由器中同时处理/products/product/:id

特定产品的正确 REST API 结构是 plural/{id},因此在您的情况下,理想情况下应该是 /products/:id

不过话虽如此,您可以使用 Regex 来匹配可选的 s

app.all('/products?/:id?', function (req, res) {
 //will match /product/id also /products/id also /product also /products
}) 

查看 official doc 了解更多信息。

假设您使用的是快速框架,那么您可以对所有请求方法使用 app.all() 路由,即 GET,POST,DELETE 并根据请求方法获取或显示条件数据。

进一步参考 https://expressjs.com/tr/guide/routing.html

示例:

const express = require('express');
var bodyParser  = require('body-parser');
const url = require('url');

const app = express();
app.use(bodyParser.json());

app.get('/', (req, res) => {
  res.send('Hello Express app!')
});

//app.all() will accept GET, POST, PUT, DELETE request method

app.all('/products', function(req, res) {

  var id = req.query.id;

  if (req.method == 'POST') {

    console.log(req.body);

    res.send('return post data');

  }
  else {

    if (id == undefined || id == null) {

      //route : GET /products

      res.send('return all products list');

    } else {

      //route : GET /products?id=1

      res.send('return individual product detail');

    }

  }

})


app.listen(3000, () => {
  console.log('server started');
});

测试:

 1. To list all products 

    Method GET /products

 2. To get individual product detail

     Method GET /products?id=2

 3. To add new product into list

     Method POST /products
     Request Body (application/json)
     {
        "name":"xyz",
        "description":"Lorem ipsum is placeholder"
    }