1

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?

user3025403
  • 1,070
  • 3
  • 21
  • 33
  • What console error do you get when you try run this? – justDan Oct 04 '16 at 21:20
  • @daniel-d: No error in the console. When I use indexRoutes and go to one of the links that should work (such as) "localhost:8080/index.html" the page simply doesn't load. – user3025403 Oct 04 '16 at 21:27
  • Did you also test your setup by trying to just hit the `/index` route to be sure you get `"Here"` in the console? Also did you try to log the response to see what was in there? – justDan Oct 04 '16 at 21:32
  • Yes. That also didn't work. I added a default ```app.get('*', ...) ``` under the ```app.get(indexRoutes, ...)``` and the response I get when I hit ```/index``` is from the default route. – user3025403 Oct 04 '16 at 21:38
  • Check out this post: http://stackoverflow.com/questions/15350025/express-js-single-routing-handler-for-multiple-routes-in-a-single-line. Looks like it's using `app.get('/:var(bla|blabla)?', ...)` to set the request parameter. – justDan Oct 04 '16 at 21:52
  • Have you tried passing the array directly? `app.get(['url1', 'url2', 'url3'], (req, res) => { console.log('here'); })` – David Espino Oct 05 '16 at 00:32
  • This is bad form, first off you shouldn't be testing for existence of the string literal to determine if a route needs to fire. Simply put app.get('/*') after all your route declarations in the main app.js file. That way if no routes can handle the specific request it gets to '/*' and your server returns console.log('here'). – Ravenous Oct 05 '16 at 12:57
  • @David Espino That works! Thanks! If you submit it as an answer, I'll officially mark that as the answer! – user3025403 Oct 05 '16 at 16:53
  • @user3025403 Done! :) glad to help – David Espino Oct 06 '16 at 00:18

1 Answers1

1

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

Regards

David Espino
  • 2,177
  • 14
  • 21