Node.js (3) connect的使用

杨甫
2023-12-01

入门示例

安装:npm install connect

编辑:connect_test.js

const app = require('connect')();
app.use((req, res, next) => {
    res.end('Hello World');
});
app.listen('3000');

启动:node connect_test.js

访问:http://localhost:3000/

页面显示:

Hello World

组合中间件

const connect = require('connect');

function logger(req, res, next){
    console.log('%s %s', req.method, req.url);
    next();
}

function hello(req, res){
    res.setHeader('Content-Type', 'text/plain');
    res.end('Hello World');
}

connect().use(logger).use(hello).listen(3000);

备注: 注意中间件的顺序

创建可组合的中间件

logger.js

function setup(format){
    const regexp = /:(\w+)/g;

    return function createLogger(req, res, next){
        const str = format.replace(regexp, (match, property) => {
            return req[property];
        });
        console.log(str);
        next();
    }
}

module.exports = setup;

connect_test.js

const connect = require('connect');
const setup = require('./logger');

function hello(req, res){
    res.setHeader('Content-Type', 'text/plain');
    res.end('Hello World join');
}

connect().use(setup(':method :url')).use(hello).listen(3000);

使用错误处理中间件(略)

 类似资料: