我检查了与此主题相关的其他帖子,但在我的代码中找不到问题。
const myMiddleware = (fn) => {
return (req, res, next) => {
var fullUrl = req.protocol + '://' + req.get('host') + req.url;
console.log(fullUrl)
next()
}
}
const app = express()
app.use('/dist', express.static(__dirname + '/client/dist'))
app.use('/static', express.static(__dirname + '/client/static'))
app.use(bodyParser.urlencoded({ extended: false }))
app.use(cookieParserMiddleware())
app.use(passport.initialize())
const server = https.createServer(options, app)
app.get('/', myMiddleware((req, res) => {
res.sendFile(__dirname + '/client/dist/index.html')
}))
app.all('*', (req, res) => {
res.redirect('/')
})
server.listen(8080, function listening() {
console.log('Listening on %d', server.address().port)
})
如果没有myMiddleware
on'/'
路径,一切都会按预期工作。myMiddleware
附加 as app.get('/', myMiddleware((req, res) => {
thenmyMiddleware
被多次调用而不res.sendFile(__dirname + '/client/dist/index.html')
被调用。
编辑:下面的错误是用 jfriend00 的解决方案修复的。被多次调用的中间件仍然存在。原因是网站图标和其他一些资产没有被app.use('/static', express.static(__dirname + '/client/static'))
线路捕获。修复路径也解决了第一个错误
最重要的是,我尝试删除下面的部分,但该应用程序根本无法运行。我的猜测是这里有 2 个错误。
app.all('*', (req, res) => {
res.redirect('/')
})
我发布了一张关于删除时的外观的图片app.all('*'..)