在我的后端REST API中,我有处理产品的路线
[GET] /products
[GET] /product/:id
[POST] /product/:id
我想在1个路由器中全部处理它们(因为所有这些路径都可以在产品上使用),但是问题是我不知道如何区分/products
和/product
。我尝试使用/product+[s]?
之类的正则表达式,但是/products/:id
也成为有效路径,应该无效。
如何在同一路由器中同时处理/products
和/product/:id
?
答案 0 :(得分:1)
特定产品的正确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
以获得更多信息。
答案 1 :(得分:0)
假设您使用的是Express框架,则可以对所有请求方法(即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"
}