Home > Mobile >  How to route to a dynamic URL expressJS?
How to route to a dynamic URL expressJS?

Time:12-12

I want to create a login page, such that when the user successfully logs in the app goes to the URL localhost:3000/:username. So for instance when a person with username johnlogs in the app should go to localhost:3000/john. I read this page on express routing https://expressjs.com/en/guide/routing.html but it does not seem to explain this. It only explains how to get the username from the URL but not the other way around (how to route to a different URL depending on the username). Any hints would be appreciated.

CodePudding user response:

You can use redirection after the user login successfully.

var express = require('express');
var app = express();

// login page
app.get('/login', function (req, res) {
  res.send(`This is login page`);
});

// login verification
app.post('/login', function (req, res) {
  // verify user
  const user = getUserByEmailAndPassword(req.body.email, req.body.password);

  // set session  
  // ...

  // redirect
  res.redirect(`/${user.username}`);
});

// private user page
app.get('/:username', function (req, res) {
  const username = req.params.username;
  res.send(`Hello ${username}`);
});
  • Related