简体   繁体   中英

Expressjs Route from Variable

I have an array:

var arr = ["/index.html", "/alternative_index.html", "/index"]

and I want the Express server to return the same thing for all these routes:

localhost:8080/index.html
localhost:8080/alternative_index.html
localhost:8080/index

This works:

app.get("/index.html|/alternative_index.html|/index", (req, res) => {
    console.log("Here")
    ...
}

So I defined a variable that is the same as the route above:

// returns "/index.html|/alternative_index.html|/index"
var indexRoutes = arr.join("|")

However, this does not work:

app.get(indexRoutes, (req, res) => {
    console.log("Here")
    ...
}

I also tried using a RegExp for indexRoutes and that also did not work.

Why is Express not registering the right route when I define it using a variable?

Have you tried passing the array directly? app.get(['url1', 'url2', 'url3'], (req, res) => { console.log('here'); })

Regards

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