简体   繁体   中英

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

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?

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!");
});

Go through express documentation.

app.get('/ab?cd', function (req, res) {
  res.send('ab?cd')
});

cd is the variable you want to excess

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