路由方法源于 HTTP 请求方法,和 express 实例相关联。 下面这个例子展示了为应用跟路径定义的 GET 和 POST 请求: - // GET method route
- app.get('/', function (req, res) {
- res.send('GET request to the homepage');
- });
- // POST method route
- app.post('/', function (req, res) {
- res.send('POST request to the homepage');
- });
复制代码Express 定义了如下和 HTTP 请求对应的路由方法: get, post, put, head, delete, options, trace, copy, lock, mkcol, move, purge, propfind, proppatch, unlock, report, mkactivity, checkout, merge, m-search, notify, subscribe, unsubscribe, patch, search, 和 connect。 app.all() 是一个特殊的路由方法,没有任何 HTTP 方法与其对应,它的作用是对于一个路径上的所有请求加载中间件。 在下面的例子中,来自 “/secret” 的请求,不管使用 GET、POST、PUT、DELETE 或其他任何 http 模块支持的 HTTP 请求,句柄都会得到执行。 - app.all('/secret', function (req, res, next) {
- console.log('Accessing the secret section ...');
- next(); // pass control to the next handler
- });
复制代码
|