Node.js学习笔记4——网络通信

2017-03-14  本文已影响30人  Realank

HTTP server

we can simply create a http server:

var http = require('http');
http.createServer(function(req, res) { 
    res.writeHead(200, {'Content-Type': 'text/html'});       
    res.write('<h1>Node.js</h1>');
    res.end('<p>Hello World</p>');
}).listen(3000);
console.log("HTTP server is listening at port 3000.");

http.Server events

http.ServerRequest

HTTP request commonly contains 2 parts: Request Header and Request Body.

http.ServerRequest also provide 3 events to control Request Body transmission.

ServerRequest properties

fetch contents of GET request

GET request can pass parameters followed by path, url module in Node.js provide a function called parse, can parse url

var http = require('http'); 
var url = require('url'); 
var util = require('util');
http.createServer(function(req, res) { 
    res.writeHead(200, {'Content-Type': 'text/plain'}); 
    res.end(util.inspect(url.parse(req.url, true)));
}).listen(3000);

//result:
// Url {
//   protocol: null,
//   slashes: null,
//   auth: null,
//   host: null,
//   port: null,
//   hostname: null,
//   hash: null,
//   search: '?name=realank&email=realank@126.com',
//   query: { name: 'realank', email: 'realank@126.com' },
//   pathname: '/user',
//   path: '/user?name=realank&email=realank@126.com',
//   href: '/user?name=realank&email=realank@126.com' }

fetch contents of POST request

waiting for Request Body is a waste of time, so by default, Node.js won't parse Request Body, if we need, we can do it by hand

//httpserverrequestpost.js
var http = require('http');
var querystring = require('querystring'); 
var util = require('util');
http.createServer(function(req, res) { 
    var post = '';
    req.on('data', function(chunk) { 
        post += chunk;
    });
    req.on('end', function() {
        post = querystring.parse(post); 
        res.end(util.inspect(post));
    });
}).listen(3000);

http.ServerResponse

It have 3 important functions

var http = require('http');
http.createServer(function(req, res) { 
    res.writeHead(200, {'Content-Type': 'text/html'});       
    res.write('<h1>Node.js</h1>');
    res.end('<p>Hello World</p>');
}).listen(3000);
console.log("HTTP server is listening at port 3000.");

HTTP client

http module provide 2 functions, http.request and http.get.

http.request(options, callback)

option is a object like associate array, stand for parameters of request.
callback is the callback function of request.

commonly used parameters of option:

callback passes a parameter, is a instance of http.ClientResponse.

http.request returns a instance of http.ClientRequest

//httprequest.js
var http = require('http');
var querystring = require('querystring');
var contents = querystring.stringify({
    name: 'realank',
    email: 'realank@126.com',
    address: 'Tianjin',
});
var options = {
    host: '127.0.0.1',
    path: '/', 
    port: 3000,
    method: 'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Content-Length' : contents.length
      }
};
var req = http.request(options, function(res) { 
    res.setEncoding('utf8');
    res.on('data', function (data) {
        console.log(data);
    });
});
req.write(contents);
req.end();

http.get(options, callback)

the simplified version of http.request, dedicated to GET request.

var http = require('http');
http.get({host: '127.0.0.1',port: 3000}, function(res) { 
    res.setEncoding('utf8');
    res.on('data', function (data) {
        console.log(data);
    });
});
1.http.ClientRequest

Instance of http.ClientRequest will be returned by http.request or http.get, stand for a ongoing HTTP request that has been established. It provide a response event.

var http = require('http');
var req = http.get({host: '127.0.0.1',port: 3000});
req.on('response', function(res) {   
    res.setEncoding('utf8');
    res.on('data', function (data) {
        console.log(data);
      });
});

http.ClientRequest also provide functions blow:

2.http.ClientResponse

It provide 3 events. data, end, close.
data event pass a parameter called chunk.

It also provide these properties:

it provide these functions:

上一篇 下一篇

猜你喜欢

热点阅读