首页 > nodejs中http的使用问题

nodejs中http的使用问题

服务端代码

// server.js
var qs = require('querystring');
require('http')
  .createServer((req, res) => {
    let body = '';
    req.on('data', (chunk) => {
      body += chunk;
    });
    req.on('end', () => {
      res.writeHead(200);
      res.end('Done');
      console.log('got name \033[90m' + qs.parse(body).name + '\033[39m\n');
    });
  })
  .listen(3000);

客户端代码

// client.js
var http = require('http'),
  qs = require('querystring');

var options = {
  host: '127.0.0.1',
  port: 3000,
  url: '/',
  method: 'post'
};

var send = (theName) => {
  http
    .request(options, (res) => {
      res.setEncoding('utf8');
      res.on('end', () => {
        console.log('\n  \033[90m  request complete!\033[39m');
        process.stdout.write('\n  your name: ');
      });
    })
    .end(qs.stringify({name: theName}));
};

process.stdout.write('\n  your name: ');
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', (name) => {
  send(name.replace('\r\n', ''));
});

我期望的结果是这样的:

但得到的结果是这样的:

客户端,没有执行到 res.on('end', () => {...}) 里面的语句,
并且当我的服务器断开时,客户端没有自动断开,
请问这是为什么呢?orz


修正:

// client.js
var http = require('http'),
  qs = require('querystring');

var options = {
  host: '127.0.0.1',
  port: 3000,
  url: '/',
  method: 'post'
};

var send = (theName) => {
  http
    .request(options, (res) => {
      res.setEncoding('utf8');
      //这里非要写一个on data不可,否则end事件不触发
      res.on('data', (chunk) => {

      });
      res.on('end', () => {
        console.log('\n  \033[90m  request complete!\033[39m');
        process.stdout.write('\n  your name: ');
      });
    })
    .end(qs.stringify({name: theName}));
};

process.stdout.write('\n  your name: ');
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', (name) => {
  send(name.replace('\r\n', ''));
});

文档里有这么一句话:

你要不“消费”data事件,就别想用end,对此我也略蒙逼,不过这是事实,你就接受吧

【热门文章】
【热门文章】