问题

在实际应用过程中,发现message pack压缩产生的二进制内容,通过HTTP请求发送到服务器之后,无法正确解析。经过简单调研后发现,原来是对服务器端程序koa的理解不充分,使用的请求对象错误导致的。这里简单放一个能跑通的例子,以作笔记。

Sample

Client

const request = require('request');
const msgpack = require('msgpack-lite');

const reqObj = {
  "req": "msgpack"
};

const reqBuffer = msgpack.encode(reqObj);

request.post({
  url: "http://127.0.0.1:3000/req",
  method: "POST",
  body: reqBuffer,
  headers: {
    "Content-Type": "application/octet-stream",
    "Content-Length": reqBuffer.length
  }
}, function(err, res, body) {
  console.log('error:', err); // Print the error if one occurred
  console.log('statusCode:', res && res.statusCode); // Print the response status code if a response was received
  console.log('body:', body);
});

Server

const Koa = require('koa');
const app = new Koa();
const koaRouter  = require('koa-router');
const msgpack = require('msgpack-lite');

const router = new koaRouter();

router.post('/req', async function(ctx) {
  // console.log(ctx.request);

  let buf = Buffer.alloc(0);
  ctx.req.on('data', function(chunk) {
    // console.log('ctx request data emit...');
    buf = Buffer.concat([buf, chunk], buf.length + chunk.length);
  });
  ctx.req.on('end', function() {
    // console.log('ctx request data end');
    console.log('decoded:', msgpack.decode(buf));
    ctx.body = 'Hello World';
  });
});

app.use(router.routes());
app.listen(3000);

EOF