onvno / pokerface

日常技术文章阅读整理
3 stars 0 forks source link

20190812 - Node接口转发及流Stream,Pipe(2) #63

Open onvno opened 4 years ago

onvno commented 4 years ago

一直希望实现一个POST请求流,目前测试以下方法可行。 实现原理:拿到请求所有数据后,再封装请求发出

发起请求

POST: localhost:3001/post

转发请求

var http = require('http');

// 创建http服务
var app = http.createServer(function (req, res) {
    if (/POST|PUT/i.test(req.method)) {

      var body = '';
      req.on('data', function (data) {
        body += data;
      });

      req.on('end', function () {
        console.log('end:', body);

        var next = http.request({
            host:     '127.0.0.1', // 目标主机
            port: '8888',
            path:     req.url, // 目标路径
            method:   req.method, // 请求方式
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded',
              'Content-Length': Buffer.byteLength(body)
            }
        }, function(sres){
            sres.pipe(res);
            sres.on('end', function(){
                console.log('done');
            });
        });

        next.write(body);
        req.pipe(next);
      });

    } else {
        // sreq.end();
    }
});
// 访问127.0.0.1:3001查看效果
app.listen(3001);
console.log('server started on 127.0.0.1:3001');

接收请求

此处主要确认是否可以收到body内容:

const Koa = require('koa');
const bodyParser = require('koa-bodyparser');
const Router = require('koa-router');

const app = new Koa()
const router = new Router();

router.post('/post', async(ctx, next) => {
  console.log("ctx.body:", ctx.request.body);
  ctx.body = 'post ok'
})

router.get('/test', (ctx, next) => {
  ctx.body = 'connect ok!'
})

// bodyParser
app.use(
  bodyParser(),
);

// 注册路由
app
  .use(router.routes())
  .use(router.allowedMethods());

const serverPort = '8888'
// 服务
app.listen(serverPort, '0.0.0.0', () => {
  console.log(`server started: http://localhost:${serverPort}`);
});

实现参考了以下:

onvno commented 4 years ago

流实现get请求

之前已经整理:

ctx.body = ctx.req.pipe(request(`https://www.google.com/?q=${ctx.query.q}`));