如果是要在一个 koa app 里面,拦截请求,转发到另一个服务,可以这样const http = require('http'); const Koa = require('koa'); const net = require('net'); const app = new Koa(); app.use((ctx, next) => { ctx.body = 'from koa app'; }); const koaServer = http.createServer(app.callback()).listen(3000); // const koaServer = app.listen(3000); // proxy server http.createServer((req, res) => { console.log(req.method); console.log(req.url); }).listen(3001); koaServer.on('connection', socket => { const proxy_socket = net.createConnection(3001) socket.on('data', chunk => { proxy_socket.write(chunk); }); socket.on('end', () => { proxy_socket.end(); }) });
如果是要在一个 koa app 里面,拦截请求,转发到另一个服务,可以这样