我使用next.js和express.js。如果我使用中间件(server.use(req,res,next)),则在页面编译时会被打数十次,这会使我的应用完全崩溃...
const express = require('express')
const next = require('next')
const port = parseInt(process.env.PORT, 10) || 3000
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
console.log('page loaded')
app.prepare().then(() => {
const server = express()
server.use((req, res, next) => {
console.log('ping')
next();
})
server.get('/', (req, res) => {
return app.render(req, res, '/index', req.query)
})
server.get('*', (req, res) => {
return handle(req, res)
})
server.listen(port, err => {
if (err) throw err
console.log(`> Ready on http://localhost:${port}`)
})
})
如果我尝试加载页面,它将打印
ping
ping
ping
ping
ping
ping
ping
ping
ping
ping
ping
ping
ping
ping
ping
当然,如果我在此处放置一个真正的中间件,它将使所有内容崩溃……
我希望仅当页面实际在请求某项内容时才运行中间件……因此每个“真实用户”请求仅需执行一次