Express: How to use colon as normal character instead of route param

Created on 16 Jan 2019  路  6Comments  路  Source: expressjs/express

Colon(:) used to define route param in Express/Koa.

app.get('/users/:userId/books/:bookId', function (req, res) {
  res.send(req.params)
})

Google API design use colon as custom verb
image

Question: Is there a way to define a route in which I want use colon as normal character ?

Target: define a route that match PUT /tasks/1234:undelete, and define with string instead of regexp.

Most helpful comment

Through trial and error, and from the express routing document guidance for treatment of $, I ended up with the following that appears to work:

app.put('/tasks/:id[\:]action', function (req, res) {});

If the dev team has any comment if that's the best way, that would be great, but seems to work. Thanks!

All 6 comments

If you use Koa koa-router, try router.put('/tasks/:_id\\:undelete').
If you use Express, maybe not for now.

Reason: path-to-regexp>=0.2 support \\:, but express use 0.1.7 currently.

Related issues: #3419 #3409 #3142 #2530

Hello is this not working yet or maybe express have done an update to done this.

You can define your route using the double colon notation and a switch statement to execute the appropriate logic based on your action.

app.put('/tasks/:id::action', function (req, res) {
  switch (req.params.action) {
    case "delete":
      return res.send("deleted")
    case "update":
      return res.send("updated")
    default:
      return res.send("invalid action")
  }
})

@kevinrambaud Do you know if there's a way to do this without having to do a match on the command itself? So, if I wanted to have actual physical routes for the different actions (/tasks/1:publish) without having the sub-routing logic?

Through trial and error, and from the express routing document guidance for treatment of $, I ended up with the following that appears to work:

app.put('/tasks/:id[\:]action', function (req, res) {});

If the dev team has any comment if that's the best way, that would be great, but seems to work. Thanks!

@patwhite You might want to open an issue at https://github.com/pillarjs/path-to-regexp to get a more definitive answer.

Was this page helpful?
0 / 5 - 0 ratings