Node.js提供了http模块,用于搭建HTTP服务端和客户端。
创建Web服务器
1 /** 2 ?* node-http 服务端 3 ?*/ 4 let http = require(‘http‘); 5 let url = require(‘url‘); 6 let fs = require(‘fs‘); 7 ?8 // 创建服务器 9 let server = http.createServer((req, res) => {10 ????// 解析请求11 ????let pathname = url.parse(req.url).pathname; // 形如`/index.html`12 ????console.log(‘收到对文件 ‘ + pathname + ‘的请求‘);13 14 ????// 读取文件内容15 ????fs.readFile(pathname.substr(1), (err, data) => {16 ????????if (err) {17 ????????????console.log(‘文件读取失败:‘ + err);18 19 ????????????// 设置404响应20 ????????????res.writeHead(404, {21 ????????????????‘Content-Type‘: ‘text/html‘22 ????????????});23 ????????}24 ????????else {25 ????????????// 状态码:20026 ????????????res.writeHead(200, {27 ????????????????‘Content-Type‘: ‘text/html‘28 ????????????});29 30 ????????????// 响应文件内容31 ????????????res.write(data.toString());32 ????????}33 34 ????????// 发送响应35 ????????res.end();36 ????});37 });38 39 server.listen(8081);40 41 console.log(‘服务运行在:http://localhost:8081,请访问:http://localhost:8081/index.html‘);
- index.html
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 ????<meta charset="UTF-8"> 5 ????<title>Node http</title> 6 </head> 7 <body> 8 ????<h1>Hi~</h1> 9 </body>10 </html>
运行server.js
,打开浏览器访问。
创建客户端
- client.js
1 /** 2 ?* node http 创建客户端 3 ?*/ 4 let http = require(‘http‘); 5 ?6 // 请求选项 7 let options = { 8 ????host: ‘localhost‘, 9 ????port: ‘8081‘,10 ????path: ‘/index.html‘11 };12 13 // 处理响应的回调函数14 let callback = (res) => {15 ????// 不断更新数据16 ????let body = ‘‘;17 18 ????res.on(‘data‘, (data) => {19 ????????body += data;20 ????});21 22 ????res.on(‘end‘, () => {23 ????????console.log(‘数据接收完成‘);24 ????????console.log(body);25 ????});26 }27 28 // 向服务端发送请求29 let req = http.request(options, callback);30 req.end();
运行server.js
,再运行client.js
。
NodeJS http模块
原文地址:https://www.cnblogs.com/cangqinglang/p/9210809.html