当前位置: 首页 > 工具软件 > koa-proxy > 使用案例 >

Nodejs koa2使用koa2-proxy-middleware实现代理

钱选
2023-12-01

一、安装

npm install --save-dev koa2-proxy-middleware

二、常规使用

const Koa = require('koa');
const proxy = require('koa2-proxy-middleware');
const bodyparser = require('koa-bodyparser');
 
const app = new Koa();
 
const options = {
  targets: {
    '/user': {
      // this is option of http-proxy-middleware
      target: 'http://localhost:3000', // target host
      changeOrigin: true, // needed for virtual hosted sites
    },
    '/user/:id': {
      target: 'http://localhost:3001',
      changeOrigin: true,
    },
    // (.*) means anything
    '/api/(.*)': {
      target: 'http://10.94.123.123:1234',
      changeOrigin: true,
      pathRewrite: {
        '/passager/xx': '/mPassenger/ee', // rewrite path
      }
    },
    // ws
    '/websocket': {
      target: 'ws://10.94.123.123:6789',
      ws: true,
      changeOrigin: true
    }
  }
}
 
app.use(proxy(options));
 
 
app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}));

http-proxy-middleware文档: https://www.npmjs.com/package/http-proxy-middleware
koa2-proxy-middleware文档: https://www.npmjs.com/package/koa2-proxy-middleware

三、配合静态服务器使用

const path = require('path');
const Koa = require('koa');
const app = new Koa();
const serve = require('koa-static');
const proxy = require('koa2-proxy-middleware');
const bodyparser = require('koa-bodyparser');

// 配置静态服务
const index = serve(path.join(__dirname) + '/dist/'); // 静态文件目录
app.use(index);

// 配置代理
const options = {
    targets: {
        '/api/(.*)': {
            target: 'http://127.0.0.1:8000',
            ws: true,
            changeOrigin: true, // 是否跨域
            pathRewrite: {
                '/api': '', // 重写路径
            },
        },
    },
};
app.use(proxy(options));
app.use(
    bodyparser({
        enableTypes: ['json', 'form', 'text'],
    })
);

const hostName = 127.0.0.1;
const port = 8888;
app.listen(port, hostName, () => {
    console.log(`服务运行在http://${hostName}:${port}`);
});

console.log('成功启动');

 类似资料: