网络操作


网络操作

一、创建服务器与客户端

创建http服务器就是那么简单!

var http = require('http');

http.createServer(function (request, response) {
    response.writeHead(200, { 'Content-Type': 'text-plain' });
    response.end('Hello World\n');
}).listen(8124);

创建客户端

var http = require('http');
var options = {
  hostname: 'www.example.com',
  port: 80,
  path: '/upload',
  method: 'POST',
  headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
  }
};

var request = http.request(options, function (response) {
  var body = [];

  console.log(response.statusCode);
  console.log(response.headers);

  response.on('data', function (chunk) {
      body.push(chunk);
  });

  response.on('end', function () {
      body = Buffer.concat(body);
      console.log(body.toString());
  });
});

request.write('Hello World');
request.end();

二、api介绍

http模块

http有下面两种使用方式。

  • 作为服务端使用时,创建一个HTTP服务器,监听HTTP客户端请求并返回响应。
  • 作为客户端使用时,发起一个HTTP客户端请求,获取服务端响应。

https模块

https模块与http模块极为类似,区别在于https模块需要额外处理SSL证书

URL模块

处理HTTP请求时url模块使用率超高,因为该模块允许解析URL、生成URL,以及拼接URL

querystring

querystring模块用于实现URL参数字符串与参数对象的互相转换。

querystring.parse('foo=bar&baz=qux&baz=quux&corge');
/* =>
{ foo: 'bar', baz: ['qux', 'quux'], corge: '' }
*/

querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' });
/* =>
'foo=bar&baz=qux&baz=quux&corge='
*/

Zlib

Zlib模块提供了数据压缩和解压的功能。当我们处理HTTP请求和响应时,可能需要用到这个模块。

net

net模块可用于创建Socket服务器或Socket客户端。

发布了231 篇原创文章 · 获赞 93 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/wobushixiaobailian/article/details/100686722