简体   繁体   English

如何在 express.js 中处理具有无限可能性的路线?

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

Looking at How handle routes in Express.js I see the example:查看如何在 Express.js 中处理路由,我看到了这个例子:

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.您将如何处理具有无限可能性的 post/get 请求。 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:例如,查看 express 上的资源和上面的代码示例,您似乎可以通过以下声明来控制当有人请求托管位置的主页时发送的响应:

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:但是,如果我有一个系统,我会不断地通过 get 请求搜索用户,如下所示:

www.website.com/users/username www.website.com/users/用户名

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? url“用户名”的部分可以是任何东西,我将如何收集该信息并根据 url 的用户名部分发送响应?

Please look into Express Routing https://expressjs.com/en/guide/routing.html请查看快速路由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. Go 通过快速文档。

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

cd is the variable you want to excess cd 是您想要超出的变量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM