使用了connect-history-api-fallback中间件后无法读取图片
vue-router 用了 history 模式,部署之后为了刷新不404使用了connect-history-api-fallback中间件,但是用了中间件后一个原本可用的读取图片的接口无法正常使用
这是显示图片接口
// get /avatar/file_id
router.get('/avatar', async (req, res, next) => {
const id = req.query.file_id
const url = await FileModel.getFilePath(id)
res.set('content-type', 'image/jpg')
fs.readFile(url, 'binary', (err, file) => {
if (err) {
console.log(err)
return;
} else {
res.writeHead(200, { 'Content-Type': 'image/jpeg' })
res.write(file, 'binary')
res.end()
return
}
})
// let stream = fs.createReadStream(url)
// let responseData = []; // 存储文件流
// if (stream) { // 判断状态
// stream.on('data', chunk => {
// responseData.push(chunk)
// })
// stream.on('end', () => {
// let finalData = Buffer.concat(responseData)
// res.write(finalData)
// res.end()
// })
// }
})
这是引入 中间件代码
const express = require('express')
const session = require('express-session')
const bodyParser = require('body-parser')
const routes = require('./routes')
const history = require('connect-history-api-fallback')
const path = require('path')
const favicon = require('serve-favicon')
const app = new express()
app.use(history())
app.use(bodyParser.urlencoded({extended: true}))
app.use(express.static(path.join(__dirname, '../dist')))
app.use(favicon(path.join(__dirname, './favicon.ico')))
const sessionStore = new session.MemoryStore({ reapInterval: 3600 * 1000 })
app.use(session({
secret: 'Stefanie Sun',
store: sessionStore,
resave: true, // 强制更新 session
saveUninitialized: true, //
cookie: { maxAge: 3600 * 1000 }, // 过期时间
rolling: true
}))
routes(app)
app.listen('4500', () => console.log('running'))
1 回复
解决了
app.use(history({
rewrites: [
{
from: /^\/api\/.*$/,
to: function(context) {
return context.parsedUrl.path
}
}
]
}))
即可