Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Server middleware #121

Open
Echo-mz opened this issue Jan 26, 2022 · 2 comments
Open

Server middleware #121

Echo-mz opened this issue Jan 26, 2022 · 2 comments

Comments

@Echo-mz
Copy link

Echo-mz commented Jan 26, 2022

No description provided.

@Echo-mz
Copy link
Author

Echo-mz commented Jan 26, 2022

服务器端渲染中间件(serverMiddleware) 属性

Nuxt 在内部创建一个连接实例,所以我们可以将我们的中间件注册到它的堆栈,并有机会提供更多的路由,如 API,而无需外部服务器。因为连接本身是一个中间件,所以注册的中间件既可以用于nuxt start,也可以用作具有编程用法的中间件,如express-template。Nuxt Modules还可以使用this.addServerMiddleware()设置serverMiddleware。

服务器端渲染中间件(serverMiddleware) vs 中间件(middleware)!

不要将它与客户端或SSR中Vue在每条路由之前调用的routes middleware混淆。serverMiddleware只是在vue-server-renderer之前在服务器端运行,可用于服务器特定的任务,如处理API请求或服务资产。
用法
如果中间件是String,Nuxt.js将尝试自动解析它。
例如:(nuxt.config.js)
`import serveStatic from 'serve-static'

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

]
}`

自定义服务器端渲染中间件 (Server Middleware)
Middleware (api/logger.js):

export default function (req, res, next) {
// req 是 Node.js http request 对象
console.log(req.path)

// res 是 Node.js http response 对象

// next是一个调用下一个中间件的函数
// 如果您的中间件不是最终执行,请不要忘记在最后调用next!
next()
}
Nuxt 配置 (nuxt.config.js):

serverMiddleware: ['~/api/logger']

@Echo-mz
Copy link
Author

Echo-mz commented Jan 26, 2022

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant