Reputation: 1627
Problem
Hi devs,
I am having trouble passing an id that has a '/' at the beginning.
This is the log
GET /api/v1/ GetAnimeInfo//anime/5226/tokyo-ghoul/Tokyo% 20Ghoul 404 0.466 ms - 1310
As you can see, He can not recognize two /
after GetAnimeInfo//
Isn't there a way expressjs allows me that pattern?
//id = '/anime/5226/tokyo-ghoul/'
//title = 'Tokyo Ghoul'
router.get('/GetAnimeInfo/:id([^/]+/[^/]+[^/]+/[^/])/:title' , (req , res , next) =>{
let id = req.params.id
let title = req.query.title;
api.getAnimeInfo(id , title)
.then(info =>{
res.status(200).json({
info
});
}).catch((err) =>{
console.log(err);
});
});
Upvotes: 0
Views: 2794
Reputation: 171
I would highly advise against doing this.
If a client is sending an erroneous double slash there is a functional bug creating that issue and you should fix the bug, not provide a weird workaround on the server - that way you end up with more robust, predictable and maintainable code in the future.
If you're trying to manipulate the server to accept double slash as part of routing, there will be no guarantee that clients will respect the behavior so you will run into situations where one browser will work and another will not.
If you have shows which begin in a slash, eg '/ShowName', that you need to account for, you should be escaping the show name with URL encoding - https://en.wikipedia.org/wiki/Percent-encoding
Upvotes: 2
Reputation: 82096
Yeah, that's unlikely to work given Express would have no idea where where the :id
ends and where the rest of the URL pattern match begins.
Can't you just parse the URL manually? Doesn't seem like it would be all that difficult e.g.
router.get('/GetAnimeInfo/:idAndTitle', (req, res, next) => {
const { idAndTitle } = req.params;
const idx = idAndTitle.lastIndexOf("/") + 1;
const id = idAndTitle.substring(0, idx);
const title = idAndTitle.substring(idx, idAndTitle.length);
...
});
Demo
const idAndTitle = '/anime/5226/tokyo-ghoul/Tokyo Ghoul';
const idx = idAndTitle.lastIndexOf("/") + 1;
const id = idAndTitle.substring(0, idx);
const title = idAndTitle.substring(idx, idAndTitle.length);
console.log(`ID=${id}`);
console.log(`Title=${title}`);
Upvotes: 0