Node.js的&安培;防爆preSS路由与参数 [英] Node.js & Express routing with parameters
问题描述
我目前在node.js中2路线的API我建立。它们是:
I currently have 2 routes in node.js for an API I am building. They are:
app.get('/api/v1/user/:userid', function (req, res) {
return res.status(200).json(GetUser());
});
和
app.get('/api/v1/user', function (req, res) {
return res.status(400).json('UserId expected');
});
正如你所看到的,两条路线实际上应该被合并成一个,例如:
As you can see, both routes actually should be combined into one, for example:
app.get('/api/v1/user/:userid', function (req, res) {
console.log('this should still show if :userid is not populated, but it does not');
if(!req.params.userid)
return res.status(400).json('UserId expected');
return res.status(200).json(GetUser());
});
然而,当我测试与邮差上面的端点,而无需在:指定用户ID
,我会得到一个超时。显然,如果我提供一个:用户ID
,我得到了相应的用户
However, when I test the above endpoint with Postman without the :userid
specified, I will get a timeout. Obviously if I supply an :userid
, I get the corresponding user.
另外我发现,的console.log
将永远不会在终端显示当:用户ID
ISN Ť规定。这是我的端子输出:
Also I have found that the console.log
will never show up in the terminal when :userid
isn't specified. This is my terminal output:
this should still show if :userid is not populated, but it does not
GET /api/v1/user/56a6861675774c1a046bf780 200 3.140 ms - 274
GET /api/v1/user/ - - ms - -
所以,上述所有使我相信,由于:用户ID
是未定义
或空
,它打破了前preSS中间件。是假设是正确的,我如何克服它?
So all the above leads me to believe that because the :userid
is undefined
or null
, that it is breaking the express middleware. Is that assumption correct and how do I overcome it?
推荐答案
的假设是正确的。对于定义的处理程序 / API / V1 /用户/:USER_ID
不能用于 / API / V1 /用户
。因此,该航线 / API / V1 /用户/
将无法办理'GET'请求。
The assumption is correct. The handler defined for /api/v1/user/:user_id
cannot be used for /api/v1/user
. As such, the route /api/v1/user/
will be unable to handle 'GET' requests.
您需要定义不同的处理程序为不同的路线。
You need to define different handlers for the different routes.
一个解决方案是使用前preSS路由器中间件来定义你的路由。
A solution would be to use Express router middleware to define your routes.
var router = express.Router();
router.route('/api/v1/user')
.get(); // define handler for multiple resources here.
router.route('/api/v1/user/:user_id')
.get(); // define handler for single resource here.
app.use('/', router);
这篇关于Node.js的&安培;防爆preSS路由与参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!