Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

接收POST数据 #122

Open
wuxianqiang opened this issue Apr 2, 2019 · 0 comments
Open

接收POST数据 #122

wuxianqiang opened this issue Apr 2, 2019 · 0 comments

Comments

@wuxianqiang
Copy link
Owner

如果请求中还带有内容部分(如 POST 请求,它具有报头和内容),内容部分需要用户自行接收和解析。通过报头的Transfer-EncodingContent-Length 即可判断请求中是否带有内容,如下所示:

var hasBody = function (req) {
  return 'transfer-encoding' in req.headers || 'content-length' in req.headers;
};

在HTTP模块解析报头结束后,报文内容部分会通过 data 事件触发,我们只需以流的方式处理即可,如下所示:

function handle(req, res) {
  if (hasBody(req)) {
    var buffers = [];
    req.on('data', function (chunk) {
      buffers.push(chunk);
    });
    req.on('end', function () {
      req.rawBody= Buffer.concat(buffers).toString();
    });
  }
}

将接收到的Buffer列表转化为一个Buffer对象后,再转换为没有乱码的字符串,暂时挂置在req.rawBody 处。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant