yzc261亚洲城官网备用地址nodejs中http的运用题目

( yzc261亚洲城官网备用地址 )

效力端代码

// 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,对此我也略蒙逼,不过这是理想,你就承受吧

(看完/读完)这篇文章有何感想! yzc261亚洲城官网备用地址的分享…

发表评论

电子邮件地址不会被公开。 必填项已用*标注