我們知道 每一個(gè)image標(biāo)簽的src屬性 會(huì)向服務(wù)器發(fā)送一次資源請(qǐng)求,那么當(dāng)要獲取的資源是另外一個(gè)服務(wù)器(其他域名)的靜態(tài)資源,事情就變得難搞了,經(jīng)過一番搜索,獲取了http-pxory-middleware 這個(gè)神器。
const Koa = require('koa')
const path = require('path')
const views = require('koa-views')
const router = require('koa-router')()
const httpProxy = require('http-proxy-middleware')
const k2c = require('koa2-connect') //神器,使得express和http的中間件可以在koa完美運(yùn)行
const app = new Koa()
// 加載模板引擎
app.use(
views(path.join(__dirname, 'src/views'), {
extension: 'ejs'
})
)
// 引入公共html頁(yè)面(骨架)
router.get('/', async ctx => {
let title = 'MideaCloud'
await ctx.render('index', {
title
})
})
app.use(async (ctx, next) => {
if (ctx.url.startsWith('/image')) {
//匹配有image字段的請(qǐng)求url
ctx.respond = false // 繞過koa內(nèi)置對(duì)象response ,寫入原始res對(duì)象,而不是koa處理過的response
await k2c(
httpProxy({
target: 'http://127.0.0.1:5001', //be proxied server
changeOrigin: true,
secure: false
})
)(ctx, next)
}
await next()
})
app.use(router.routes())
let host = '127.0.0.1'
let port = 8001
app.listen(port, host, () => {
console.log(`服務(wù)運(yùn)行在http://${host}:${port}`)
})
btw 親測(cè) koa 的koa-proxy-middleware 無(wú)效。。。 建議有這個(gè)需求的親合理避雷
補(bǔ)充一下: ejs里面是醬紫的
<image src="image/zoya/littleGilr.jpg">
然后這個(gè)/image/ 前綴的 src 指向的就是你要去獲取的服務(wù)器的資源啦
再補(bǔ)充一下:if you 喜歡 html 頁(yè)面 不喜歡ejs 如下
// 加載模板引擎
app.use(
views(path.join(__dirname, 'src/views'), {})
)