Warm tip: This article is reproduced from serverfault.com, please click

how to handle routes with limitless possibilities in express.js?

发布于 2020-12-02 08:04:55

Looking at How handle routes in Express.js I see the example :

var express = require("express");

var app = express();

app.get("/", function(request, response) {
  response.send("Welcome to the homepage!");
});

app.get("/about", function(request, response) {
  response.send("Welcome to the about page!");
});

app.get("*", function(request, response) {
  response.send("404!");
});

app.listen(1337);

as a clear example to handle routes , but one thing is unclear. How would you handle post/get requests with infinite possibilities. For example , looking at the resources on express and in the code example above, it seems that you can control the response sent when someone requests the home page of the hosted location by declaring :

app.get("/", function(request, response) {
  response.send("Welcome to the homepage!");
});

but what if I had a system where I would am constantly searching for users via get requests like this:

www.website.com/users/username

the portion of the url "username" could be anything , How would I gather that information and send a response based on the username portion of the url?

Questioner
RonRon Scores
Viewed
0
NS23 2020-12-02 16:09:38

Please look into Express Routing https://expressjs.com/en/guide/routing.html

In your case route can be.

app.get("/user/:username", function(request, response) {
   const {username} = request.params;
  response.send("Welcome to the homepage!");
});