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');



你可能感兴趣的:(node,express)