JXtreehouse / nodejs-lessions

一个node学习记录仓库
3 stars 2 forks source link

http-proxy-middleware #6

Open AlexZ33 opened 5 years ago

AlexZ33 commented 5 years ago

npm模块之http-proxy-middleware使用教程(译)

AlexZ33 commented 5 years ago

const Koa = require('koa')
const app = new Koa()
const httpProxy = require('http-proxy-middleware');
const k2c = require('koa2-connect');
const bodyparser = require('koa-bodyparser')

/**
* 使用http代理请求转发,用于代理页面当中的http请求
* 这个代理请求得写在bodyparse的前面,
* 
*/
app.use(async(ctx, next) => {
    if (ctx.url.startsWith('/api')) { //匹配有api字段的请求url
       ctx.respond = false // 绕过koa内置对象response ,写入原始res对象,而不是koa处理过的response
        await k2c(httpProxy({
        target: 'http://192.168.50.60:3000', 
        changeOrigin: true,
        secure: false,
        pathRewrite: {
        '^/api': ''
            }
        }
        ))(ctx,next);
    }
    await next()
})

app.use(bodyparser({
enableTypes:['json', 'form', 'text']
}))
.......等等一大堆中间件

module.exports = app

总结,大部分是从网上收集到的知识点混合在一起,完成http-proxy的代理,期间使用过几个专门给koa2使用的http-proxy,但是大部分核心部分还是依赖于http-proxy-middleware这个依赖包的

koa2-proxy-middleware


const httpProxy = require('http-proxy-middleware');
const k2c = require('koa2-connect');
const pathToRegexp = require('path-to-regexp');

module.exports = (options) => {
  return async function (ctx, next) {
    const { targets = {} } = options;
    const { path } = ctx;
    for (const route of Object.keys(targets)) {
      if (pathToRegexp(route).test(path)) {
        await k2c(httpProxy(targets[route]))(ctx, next);
        break;
      }
    }
    await next();
  };
};
AlexZ33 commented 5 years ago

项目实例: https://github.com/KeyonY/NodeMiddle https://github.com/HereSinceres/nodeMiddleWay

AlexZ33 commented 5 years ago

express

var proxyMiddleware = require('http-proxy-middleware')
var express = require('express')
// 代理配置
var proxyTable = config.dev.proxyTable

// 载入代理配置
Object.keys(proxyTable).forEach(function (context) {
  var options = proxyTable[context]
  if (typeof options === 'string') {
    options = { target: options }
  }
  app.use(proxyMiddleware(options.filter || context, options))
})
AlexZ33 commented 5 years ago

config.js

module.exports = {
   proxyTable: {

   }
}
AlexZ33 commented 5 years ago

https://github.com/chimurai/http-proxy-middleware