ExpressJS – Recommended way of defining routes

微信扫一扫,分享到朋友圈

ExpressJS – Recommended way of defining routes

I am stuck with kind of a silly thing. There are two possible options (actions) that the user can choose. How should the routes be defined or what’s the recommended way of defining in this case?

Paths:

.com/email/register
.com/email/verify

Variant 1: Keeping every route separate on a new line

app.VERB("/email/register", SomeObject.register);
app.VERB("/email/verify", SomeObject.verify);

Variant 2: Keeping all the options in one block (callback)

app.VERB("/email/:action", function(req, res) {
var action = req.params.action;
if (action === "register" || action === "verify") {
SomeObject[action](req, res);
}
else {
res.send(404);
}
});

Problem courtesy of: 0101

Solution

It really depends on your use case, but if you’ve only got two options I’d recommend the first variant,

app.VERB("/email/register", register_handler)
app.VERB("/email/verify", verify_handler)

The second method is useful if you’ve got a large number of possible actions and they share similar handling code; for example, a custom API that you’ll be calling through the frontend.

Solution courtesy of: furydevoid

微信扫一扫,分享到朋友圈

ExpressJS – Recommended way of defining routes

丁香医生VS搜狗:疫情动态哪家强

上一篇

Angular对接Spring Get、Put、Post、Delete请求

下一篇

你也可能喜欢

ExpressJS – Recommended way of defining routes

长按储存图像,分享给朋友