1

I am building a slack copy cat app for practice and want to implement the ability for users to create their own messaging space. When creating a message space, a unique key is created and stored to my database. My plan is to use these unique keys to serve the same html page that has the messaging functionality. In theory this would work, but I am having trouble retrieving the keys AND using them to route to my message.html file. Is there a way to run my server, retrieve the keys and store them to a global variable THEN route to the html page? I'm using Node, Express and MongoDB.

Here is what my code looks like on the back end to retrieve the keys:

var dbKeys = [];
db.messageSpaces.find({}, {"_id": 0, "name": 0}, function(error, data) {
    if (error) {
      console.log(error);
    }
    else {
    for (var i = 0; i < data.length; i++) {
        dbKeys.push(data[i].key);
    }
  }
});

And how I am attempted to route them:

for (var i = 0; i < dbKeys.length; i++) {
    app.get(`/${dbKeys[i]}`, function(req, res) {
        res.sendFile(path.join(__dirname, "public/message.html"));
    });
}
1
  • 1
    I don't think you want to be defining an express route [app.get()] inside a for loop. You want to define a route with a parameter which is a placeholder for your key. Refer Route Parameters in the express docs: expressjs.com/en/guide/routing.html Commented Sep 21, 2017 at 3:10

1 Answer 1

1

I think I would use a single call to app.get and use one of the techniques described in https://expressjs.com/en/guide/routing.html#route-parameters to perform basic validation of the format. Perhaps something like this:

app.get('/:id([a-z0-9]{16})', function(req, res) {
    console.log(req.params.id);    
});

The above assumes that an id is 16 characters long and consists of lowercase letters and numbers only.

You would then check whether the message space id corresponds to a real message space inside the get handler. If it doesn't you could either handle the error or pass it on down the middleware chain by calling next() (you would need to add next as an argument to your handler for that to work).

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for this! I'll give it a shot and get back to ya.
Hey I know this response is a little late, but this worked perfectly for me! Good to know for future projects as well! Thanks again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.