[英]What is the express.js equivalent of the node.js http module's “req.url”?
When using vanilla node.js' http.createServer, you can get the url that the client requested with req.url. 当使用vanilla node.js的http.createServer时,您可以通过req.url获得客户端请求的url。
When using express.js, the code for responding to a HTTP GET request is something like: 使用express.js时,用于响应HTTP GET请求的代码如下:
app.get('/', function (req, res) {
res.send('Hello World!')
})
My problem with this is that it requires you to have an individual app.get for every single page or item on the server. 我的问题是,它要求您为服务器上的每个页面或项目都拥有一个单独的app.get。 How do I use express.js like the vanilla node.js server to deal with each get request within the callback generated by the http.createServer?
我该如何使用vanilla node.js服务器之类的express.js处理由http.createServer生成的回调中的每个get请求?
Register you followup handler like an express module... 注册您的后续处理程序,例如快速模块...
app.use(function(req, res, next){ ... YOUR CODE HERE ... })
Do this after your routes... 在您的路线之后执行此操作...
Hi 你好
To answer the specific question (as outlined in your title) , ExpressJS provides 为了回答特定的问题(如标题中所述) ,ExpressJS提供了
So, essentially, Express' req.baseUrl + req.url is equivalent to Node's req.url 因此,从本质上讲 ,Express的req.baseUrl + req.url等同于Node的req.url
Also, Express' routing DOES NOT require you to explicitly set the path to each page; 此外,Express的路由不要求你明确地将路径设置为每个页面; it also accepts regex strings with which you can process specific requests.
它还接受可用于处理特定请求的正则表达式字符串。
Take a look at Express' routing ; 看一下Express的路由 ; it should be of immense benefit to you.
它应该给您带来巨大的好处。
You shouldn't ever have a need to use req.url
. 您永远不需要使用
req.url
。 Express allows you to have variables in your routes. Express允许您在路线中包含变量。
app.get('/article/:id', function(req, res) {
// req.params.id will be whatever came after /article/
});
You can also get fancy and use a regular expression. 您也可以看中并使用正则表达式。
app.get(/\/article(\d+)/, function(req, res) {
// req.params[0] will have the digits of /article123
});
If you really want the URL, req.url
still exists. 如果您确实想要该URL,则
req.url
仍然存在。 However, you should use routes to handle all your routing logic. 但是,您应该使用路由来处理所有路由逻辑。 I've never really had the need to use
req.url
. 我从来没有真正需要使用
req.url
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.