繁体   English   中英

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

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

查看如何在 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);

作为处理路线的一个明显例子,但有一件事尚不清楚。 您将如何处理具有无限可能性的 post/get 请求。 例如,查看 express 上的资源和上面的代码示例,您似乎可以通过以下声明来控制当有人请求托管位置的主页时发送的响应:

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

但是,如果我有一个系统,我会不断地通过 get 请求搜索用户,如下所示:

www.website.com/users/用户名

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

请查看快速路由https://expressjs.com/en/guide/routing.html

在你的情况下路线可以。

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

Go 通过快速文档。

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

cd 是您想要超出的变量

暂无
暂无

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

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