express 学习笔记(一)router

API:

1、app.use([path],function);

path: 可选, 默认参数--'/'

function:中间件

              1. == function(request, response, next)

              2.无参多个

2、app.VERB[path, [callback...], callback);

VERB: *get, *post, put, delete

path: String or Regex

callback: *next()  *next('router') 意义不一样


3、app.param();


代码:app.use

var express = require('express');
var app = express();

app.use(express.static(__dirname + '/static'));

app.use(function (request, response, next) {
    console.log('Incoming Request ' + request.method + " to " + request.url);
    if ('/' == request.url) {
        response.writeHead(200, {'Content-Type': 'text/plain'});
        response.end('This is home!\n');
    } else {
        next();
    }
});

app.use(function (request, response, next) {
    if ('/about' == request.url) {
        response.writeHead(200, {'Content-Type': 'text/plain'});
        response.end('This is maizi.edu!\n');
    } else {
        next();
    }
});

app.use(function (request, response, next) {
    response.writeHead(404, {'Content-Type': 'text/plain'});
    response.end('404 not found!\n');
});

app.listen(1234, 'localhost');

代码:app.VERB

var express = require('express');
var app = express();

app.get('/', function (request, response, next) {
    console.log(1);
    // response.send('Hello World\n');
    next();
}, function (request, response, next) {
    console.log(2);
    next('route');
});

app.get('/', function (request, response, next) {
    console.log(3);
    // response.send('Hello World\n');
    next();
}, function (request, response, next) {
    console.log(4);
    response.send('Hello World\n');
});

app.param('listname', function (request, response, next, listname) {
    console.log('params');
    console.log(listname);

    // do some checking
    request.list = ['item0', 'item1', 'item2'];
    next();
});

app.get('/list/:listname', function (request, response, next) {
    console.log(6);
    // console.log(request.list);
    response.send('list:\n' + request.list.join(' '));
});

app.get('/list/:listname/:id', function (request, response, next) {
    console.log(7);
    var listname = request.params.listname;
    var id = request.params.id;
    response.send(request.list[id]);
});

app.listen(1234, 'localhost');



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值