nuxt.js 官网 https://zh.nuxtjs.org/
serverMiddleware方法: https://zh.nuxtjs.org/api/configuration-servermiddleware
使用serverMiddleware的目的:
使用过express,koa等node框架的小伙伴相信都会知道中间件的作用。
- 不知道怎么使用的看这里:
- express: http://expressjs.com/en/4x/api.html#app.use
- koa2: https://koa.bootcss.com/
在项目中,我想要在页面渲染之前来控制一些操作,请注意这个页面渲染之前不是指浏览器中的事件,而是服务端html模板和数据组装前;
比如我要在终端输出当前client端发起的请求及相应时间和状态,并根据其做优化处理,我可以引入morgan
模块(地址:https://www.npmjs.com/package/morgan),然后在nuxt.config.js
中
const logger = require('morgan');
serverMiddleware: [
logger('dev')
]
然后通过终端即可看到如下显示
GET / 200 190.107 ms - 101022
GET /register 200 94.172 ms - 106428
使用方法:
export default {
serverMiddleware: [
// Will register redirect-ssl npm package
'redirect-ssl',
// Will register file from project api directory to handle /api/* requires
{ path: '/api', handler: '~/api/index.js' },
// We can create custom instances too
{ path: '/static2', handler: serveStatic(__dirname + '/static2') }
]
}
nuxt加载中间件的源码:
// Add user provided middleware
for (const m of this.options.serverMiddleware) {
this.useMiddleware(m);
}
useMiddleware(middleware) {
let handler = middleware.handler || middleware;
// Resolve handler setup as string (path)
if (typeof handler === 'string') {
try {
const requiredModuleFromHandlerPath = this.nuxt.resolver.requireModule(handler);
// In case the "handler" is not derived from an object but is a normal string, another object with
// path and handler could be the result
// If the required module has handler, treat the module as new "middleware" object
if (requiredModuleFromHandlerPath.handler) {
middleware = requiredModuleFromHandlerPath;
}
handler = requiredModuleFromHandlerPath.handler || requiredModuleFromHandlerPath;
} catch (err) {
consola.error(err);
// Throw error in production mode
if (!this.options.dev) {
throw err
}
}
}
// Resolve path
const path = (
(middleware.prefix !== false ? this.options.router.base : '') +
(typeof middleware.path === 'string' ? middleware.path : '')
).replace(/\/\//g, '/');
// Use middleware
this.app.use(path, handler);
}
// Create new connect instance
this.app = connect();
在此我们看到中间件其实是通过this.app.use
加载的,但是……
让我们充满期待的去看看 this.app
是谁……
注:我的项目是基于koa创建的
const connect = _interopDefault(require('connect'));
// Create new connect instance
this.app = connect();
终于知道为什么我写的中间件为什么一直报错
我的中间件模式(koa中间件语法):
module.exports = async (ctx,next) => {
//...others code
}
修改后:
module.exports = (req, res, next) => {
// ...others code
};
不错,不能使用async
,想哭……
网友评论