When using vanilla node.js' http.createServer, you can get the url that the client requested with req.url.
When using express.js, the code for responding to a HTTP GET request is something like:
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. 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?
You shouldn't ever have a need to use req.url
. Express allows you to have variables in your routes.
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. However, you should use routes to handle all your routing logic. I've never really had the need to use req.url
.
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句