[英]param type in route of express.js
In express.js, if I have this route in my server side 在express.js中,如果我在服务器端拥有此路由
router.get('/ad/:id', (req, res) => {
const { id } = req.params
Ad.getAd(id, (err, resp) => {
if(err){
return handleError('Failed to load an ad', res)
}
res.json({
success: true,
result: resp
})
})
})
and it worked fine I want to load a detail ad like example.com/ad/123
where id is 123. But I can't do example.com/ad/create
anymore, any way to check the type of the param? 而且效果很好,我想加载一个诸如example.com/ad/123
类的详细广告,其中id为123。但是我再也无法执行example.com/ad/create
了,可以用任何方法检查参数的类型吗?
You can create separate route for it. 您可以为其创建单独的路由。 Place before /ad/:id
route, because it's catching all requests like /ad/*
. 放在/ad/:id
路由之前,因为它可以捕获/ad/*
类的所有请求。
router.get('/ad/create', (req, res) => { /* some work */ })
router.get('/ad/:id', (req, res) => { /* some work */ })
Since you mentioned you are building a SPA, you must redirect all GET requests to react-router: 由于您提到要构建SPA,因此必须将所有GET请求重定向到react-router:
app.get("*", function (req, res) {
res.sendFile(__dirname + "/path/to/index.html")
})
Also you can prepend api
to all back-end endpoints to prevent ambiguity. 您也可以在所有后端端点之前添加api
,以防止产生歧义。
router.get('/api/ad/create', (req, res) => { /* some work */ })
router.get('/api/ad/:id', (req, res) => { /* some work */ })
router.get('/ad/:id', (req, res,next) => {
const { id } = req.params
if(! parseInt(id,10)){
return next();//skip this route if not a number
}
//its a number
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.