I'm testing an Express API using the post method.
The request body is like
{
"menuId": "id2-test",
"menuName": "test menu name 2",
"menuUrl": "/admin/menu/test",
"desc": "this is test menu 2 description",
"menuOrder": 2,
"usageStatus": "true"
}
As you could see there is a property menuUrl which is a path of a valid URL. So to make sure user can enter the valid value for all provided properties. I've tried to validate the menuUrl using Regex
router.post(
"/",
validate(paramValidation.createMenu),
async (req, res, next) => {
const { userInfo } = req;
const menu = new Menus({
menuUrl: req.body.menuUrl,
...req.body,
});
// Regex validation is here
if (!menu?.menuUrl.match(/^[a-z][a-z0-9+.-]*:/)) {
return new ApiError("MENU_URL_NOT_VALID", httpStatus.BAD_REQUEST, true);
}
menu.createdBy = userInfo.userNm;
await Menus.findOne({ menuId: menu.menuId })
.then((_menu) => {
if (!_menu) {
return menu.save();
}
const err = new ApiError("ROLE_ALREADY", httpStatus.BAD_REQUEST, true);
return Promise.reject(err);
})
.then((_menu) => {
res.status(httpStatus.CREATED).json(_menu);
return null;
})
.catch((e) => next(e));
}
);
However, When the request is made, I received the error that said that could not get response. If I remove the Regex validation step above, and then everything still working fine. What happened with that?