本文实例讲述了NodeJS http模块用法。分享给大家供大家参考,具体如下:
Node.js提供了http模块,用于搭建HTTP服务端和客户端。
创建Web服务器
/** * node-http 服务端 */ let http = require('http'); let url = require('url'); let fs = require('fs'); // 创建服务器 let server = http.createServer((req, res) => { // 解析请求 let pathname = url.parse(req.url).pathname; // 形如`/index.html` console.log('收到对文件 ' + pathname + '的请求'); // 读取文件内容 fs.readFile(pathname.substr(1), (err, data) => { if (err) { console.log('文件读取失败:' + err); // 设置404响应 res.writeHead(404, { 'Content-Type': 'text/html' }); } else { // 状态码:200 res.writeHead(200, { 'Content-Type': 'text/html' }); // 响应文件内容 res.write(data.toString()); } // 发送响应 res.end(); }); }); server.listen(8081); console.log('服务运行在:http://localhost:8081,请访问:http://localhost:8081/index.html');
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Node http</title> </head> <body> <h1>Hi~</h1> </body> </html>
运行server.js,打开浏览器访问。
创建客户端
client.js
/** * node http 创建客户端 */ let http = require('http'); // 请求选项 let options = { host: 'localhost', port: '8081', path: '/index.html' }; // 处理响应的回调函数 let callback = (res) => { // 不断更新数据 let body = ''; res.on('data', (data) => { body += data; }); res.on('end', () => { console.log('数据接收完成'); console.log(body); }); } // 向服务端发送请求 let req = http.request(options, callback); req.end();
运行server.js,再运行client.js。
希望本文所述对大家node.js程序设计有所帮助。
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件!
如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
狼山资源网 Copyright www.pvsay.com
暂无“NodeJS http模块用法示例【创建web服务器/客户端】”评论...
RTX 5090要首发 性能要翻倍!三星展示GDDR7显存
三星在GTC上展示了专为下一代游戏GPU设计的GDDR7内存。
首次推出的GDDR7内存模块密度为16GB,每个模块容量为2GB。其速度预设为32 Gbps(PAM3),但也可以降至28 Gbps,以提高产量和初始阶段的整体性能和成本效益。
据三星表示,GDDR7内存的能效将提高20%,同时工作电压仅为1.1V,低于标准的1.2V。通过采用更新的封装材料和优化的电路设计,使得在高速运行时的发热量降低,GDDR7的热阻比GDDR6降低了70%。