nodejs 中间件

1:全集中间件

复制代码
//导入模块
const express = require('express');
//创建应用
const app = express();

function logger(req, resp, next) { 
    console.log(`${req.method} ${req.path} "${req.headers['user-agent']}"`);
    next();
}
app.use(logger); //注冊中間件
app.get('/',(req,resp)=>{
    //输出响应
    console.log('request coming.............');
    resp.send("hello world");
});

app.listen(8080,()=>{
    console.log('listening on 8080');
});

执行结果:

GET / "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36"

request coming...

GET /.well-known/appspecific/com.chrome.devtools.json "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36"

路由中间件:

复制代码
//导入模块
const express = require('express');
//创建应用
const app = express();

function logger(req, resp, next) { 
    console.log(`${req.method} ${req.path} "${req.headers['user-agent']}"`);
    next();
}

app.get('/',logger,(req,resp)=>{ //注册到路由上
    //输出响应
    console.log('request coming.............');
    resp.send("hello world");
});

app.listen(8080,()=>{
    console.log('listening on 8080');
});

``
可配置中间件:

//导入模块

const express = require('express');

//创建应用

const app = express();

function logger(options) {

return function (req, resp, next) {

const logs = [];

if (options.method) {

logs.push(req.method);

}

if (options.path) {

logs.push(req.path);

}

if (options['user-agent']) {

logs.push(req.headers['user-agent']);

}

console.log(logs.join(' '));

next();

};

}

app.use(logger({ method: true, path: true }));

app.get('/',(req,resp)=>{

//输出响应

console.log('request coming...');

resp.send("hello world");

});

app.get('/user',(req,resp)=>{

//输出响应

console.log('request coming...');

resp.send("hello user");

});

app.listen(8080,()=>{

console.log('listening on 8080');

});

复制代码
**响应时长中间件**

//导入模块

const express = require('express');

//创建应用

const app = express();

function responseTime(req,resp,next) {

const start = Date.now();

resp.once('finish', function () {

console.log('处理时长',Date.now() - start);

});

next();

}

app.use(responseTime);

app.get('/',(req,resp)=>{

//输出响应

setTimeout(() => {

console.log('request coming...');

resp.send("hello world");

},1000);

});

app.listen(8080,()=>{

console.log('listening on 8080');

});

复制代码
**静态资源中间件**
express.static(root,[options])

//导入模块

const express = require('express');

//创建应用

const app = express();

app.use('/public',express.static('./public'));

app.listen(8080,()=>{

console.log('listening on 8080');

});

复制代码