在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/HTML/ node express項目中使用了connect-history-api-fa

node express項目中使用了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')
    let stream = fs.createReadStream(url)
    let responseData = []; // 存儲文件流
    if (stream) { // 判斷狀態(tài)
        stream.on('data', chunk => {
            responseData.push(chunk)
        })
        stream.on('end', () => {
            let finalData = Buffer.concat(responseData)
            res.write(finalData)
            res.end();
        });
    }
})

FileModel.getFilePath 代碼如下

// 獲取文件路徑
handleFile.getFilePath = async function  (id) {
    let fileObject = await handleFile.getFileById(id)
    return path.join(__dirname, `../uploads/${fileObject.filename}`)
}

index.js 引入 history 代碼如下

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)

但是在界面中使用獲取圖片接口時報了 304 且獲取不到文件

clipboard.png

我將 history 刪掉后就一切正常
求問這個怎么解決

回答
編輯回答
冷眸

解決了,其實是用了connect-history-api-fallback中間件后所有的get請求都會變成index,所以get請求根本沒有執(zhí)行,設置rewrites就行了

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

設置了rewrites之后表示所有帶api的get都代理到parsedUrl.path,其實就是原來的路徑

2017年6月2日 12:31
編輯回答
心沉

這個包是干啥的啊,能對stream流使用嗎

2018年6月22日 10:55