Regex for route matching in Express

走远了吗. 提交于 2020-01-08 16:06:36

问题


I'm not very good with regular expressions, so I want to make sure I'm doing this correctly. Let's say I have two very similar routes, /discussion/:slug/ and /page/:slug/. I want to create a route that matches both these pages.

app.get('/[discussion|page]/:slug', function(req, res, next) {
  ...enter code here...
})

Is this the correct way to do it? Right now I'm just creating two separate routes.

someFunction = function(req, res, next) {..}
app.get('/discussion/:slug', someFunction)
app.get('/page/:slug', someFunction)

回答1:


app.get('/:type(discussion|page)/:id', ...) works




回答2:


You should use a literal javascript regular expression object, not a string, and @sarnold is correct that you want parens for alternation. Square brackets are for character classes.

const express = require("express");
const app = express.createServer();
app.get(/^\/(discussion|page)\/(.+)/, function (req, res, next) {
  res.write(req.params[0]); //This has "discussion" or "page"
  res.write(req.params[1]); //This has the slug
  res.end();
});

app.listen(9060);

The (.+) means a slug of at least 1 character must be present or this route will not match. Use (.*) if you want it to match an empty slug as well.



来源:https://stackoverflow.com/questions/10858005/regex-for-route-matching-in-express

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!