api用fs stream获取图片返回304 with connect-history-api-fallback

时间:2018-05-14 03:52:11

标签: node.js express

获取图片的代码

// 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')
  let stream = fs.createReadStream(url)
  let responseData = []; // 存储文件流
  // res['cache-control'] = 'no-store'
  if (stream) { // 判断状态
    stream.on('data', chunk => {
      responseData.push(chunk)
    })
    stream.on('end', () => {
      let finalData = Buffer.concat(responseData)
      res.write(finalData)
      res.end();
    });
  }
})
带有connect-history-api-fallback 的

代码
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('80', () => console.log('running'))

我不能以这种方式得到我的照片 enter image description here enter image description here

但是当我删除connect-history-api-fallback时,它可以工作!

1 个答案:

答案 0 :(得分:0)

我发现所有获取请求将使用此中间件代理索引,并且我可以重写请求

app.use(history({
    rewrites: [
      {
        from: /^\/api\/.*$/,
        to: function(context) {
            return context.parsedUrl.path
        }
      }
    ]
 }))

然后它起作用