简体   繁体   中英

express app get pattern is throwing “Cannot GET”

I have the following type of pages:

  1. root ( / )
  2. todays chapter ( /929 OR /929/ ) which eventually redirects to /929/<CHAPTER> where <CHAPTER> is a natural number between 1 to 929
  3. chapters ( /929/<CHAPTER> OR /929/<CHAPTER>/ ) where <CHAPTER> is a natural number between 1 to 929
  4. articles about the chapters ( /929/<CHAPTER>/<ARTICLE_ID> OR /929/<CHAPTER>/<ARTICLE_ID>/ ), where <CHAPTER> is a natural number between 1 to 929 and is a natural number like 1,2...99999999

1 to 3 page types work fine. The fourth is throwing:

Cannot GET /929/233/3027

Here's code:

app.get("/", rootMiddleware);
app.get("/929[/]{0,1}", todaysChapterMiddleware);
app.get("/929/:chapter(([1-9]|[1-9][0-9]|[1-8][0-9]{2}|9[01][0-9]|92[0-9]))[/]{0,1}", chapterMiddleware);
app.get("/929/:chapter(([1-9]|[1-9][0-9]|[1-8][0-9]{2}|9[01][0-9]|92[0-9]))/:articleId((\d+))[/]{0,1}", articleMiddleware);

Because the regular expression is usually part of a literal string, be sure to escape any \\ characters with an additional backslash, for example \\\\d+.

So the correct fourth route should be:

app.get("/929/:chapter(([1-9]|[1-9][0-9]|[1-8][0-9]{2}|9[01][0-9]|92[0-9]))/:articleId((\\d+))[/]{0,1}", articleMiddleware);

add \\ to escape the \\

so

from

app.get("/929/:chapter(([1-9]|[1-9][0-9]|[1-8][0-9]{2}|9[01][0-9]|92[0-9]))/:articleId((\d+))[/]{0,1}", articleMiddleware);

to

app.get("/929/:chapter(([1-9]|[1-9][0-9]|[1-8][0-9]{2}|9[01][0-9]|92[0-9]))/:articleId((\\d+))[/]{0,1}", articleMiddleware);

In app.js main file:

app.use("/",routesfile);

In routes file:

router.get('/929/<CHAPTER>',controller file)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM