官术网_书友最值得收藏!

Handling dynamic URLs and the HTML forms

The Express framework also supports dynamic URLs. Let's say we have a separate page for every user in our system. The address to those pages looks like the following code:

/user/45/profile

Here, 45 is the unique number of the user in our database. It's of course normal to use one route handler for this functionality. We can't really define different functions for every user. The problem can be solved by using the following syntax:

var getUser = function(req, res, next) {
  res.send("Show user with id = " + req.params.id);
}
app.get('/user/:id/profile', getUser);

The route is actually like a regular expression with variables inside. Later, that variable is accessible in the req.params object. We can have more than one variable. Here is a slightly more complex example:

var getUser = function(req, res, next) {
  var userId = req.params.id;
  var actionToPerform = req.params.action;
  res.send("User (" + userId + "): " + actionToPerform)
}
app.get('/user/:id/profile/:action', getUser);

If we open http://localhost:3000/user/451/profile/edit, we see User (451): edit as a response. This is how we can get a nice looking, SEO-friendly URL.

Of course, sometimes we need to pass data via the GET or POST parameters. We may have a request like http://localhost:3000/user?action=edit. To parse it easily, we need to use the native url module, which has few helper functions to parse URLs:

var getUser = function(req, res, next) {
  var url = require('url');
  var url_parts = url.parse(req.url, true);
  var query = url_parts.query;
  res.send("User: " + query.action);
}
app.get('/user', getUser);

Once the module parses the given URL, our GET parameters are stored in the .query object. The POST variables are a bit different. We need a new middleware to handle that. Thankfully, Express has one, which is as follows:

app.use(express.bodyParser());
var getUser = function(req, res, next) {
  res.send("User: " + req.body.action);
}
app.post('/user', getUser);

The express.bodyParser() middleware populates the req.body object with the POST data. Of course, we have to change the HTTP method from .get to .post or .all.

If we want to read cookies in Express, we may use the cookieParser middleware. Similar to the body parser, it should also be installed and added to the package.json file. The following example sets the middleware and demonstrates its usage:

var cookieParser = require('cookie-parser');
app.use(cookieParser('optional secret string'));
app.get('/', function(req, res, next){
    var prop = req.cookies.propName
});
主站蜘蛛池模板: 舟山市| 三河市| 格尔木市| 肥西县| 隆回县| 怀集县| 合江县| 民和| 南靖县| 鄂伦春自治旗| 博罗县| 阿城市| 临江市| 顺义区| 含山县| 中西区| 资源县| 衡水市| 高要市| 铁岭县| 江门市| 五莲县| 泰和县| 海南省| 龙井市| 腾冲县| 吉隆县| 苗栗市| 青海省| 德保县| 邹城市| 双城市| 乐至县| 弥勒县| 哈巴河县| 林芝县| 扎囊县| 双桥区| 辽阳县| 礼泉县| 洪洞县|