一、創建服務器與客戶端
創建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客戶端。