输入搜索…

· server · 1 min 阅读

Koa 代理图片

Koa 作为上传中间件,并设置代理

Koa 代理图片

@neom

  1. koa 代理图片上传中间件
    const axios = require('axios')
module.exports = async (ctx, next) => {
  var req = ctx.req
  var p = new Promise((resolve, reject) => {
    var buffers = []
    req.on('data', chunk => {
      buffers.push(chunk)
    })
    req.on('end', async () => {
      let requestBody = Buffer.concat(buffers)
      axios({
        url: `https://i.qtum-cat.com/api/v1/upload`,
        method: 'POST',
        headers: {
          'content-type': req.headers['content-type'],
          Authorization: `*****************`
        },
        data: requestBody
      })
        .then(res => {
          resolve(res.data)
        })
        .catch(err => {
          reject(err)
        })
    })
    req.on('error', function () {
      ctx.body = {
        code: 0,
        message: '获取上传文件失败'
      }
    })
  })
  var info = await p
  if (info.status) {
    ctx.lskyInfo = info.data
    await next()
  } else {
    ctx.body = {
      code: 0,
      message: '上传文件到图床失败'
    }
  }
}
  1. koa 代理转发(转发兰空图床失败)
    var proxy = require('koa-better-http-proxy')
var Koa = require('koa')
const router = require('koa-router')()
var app = new Koa()
router.get(
  '/test',
  proxy('localhost:4189', {
    proxyReqPathResolver: function (ctx) {
      return '/test' //自定义路径
    },
    proxyReqOptDecorator: function (proxyReqOpts, ctx) {
      proxyReqOpts.headers.token = '123' //自定义请求头部
      return proxyReqOpts
    }
  })
)
app.use(router.routes())
app.use(router.allowedMethods())
app.listen('3000')
分享:
返回文章列表