NodeJS http模块
来源:互联网 发布:通信网络系统组成 编辑:程序博客网 时间:2024/06/05 20:20
前言
本人所发的NodeJS系列学习笔记参考了一些书籍、官方文档以及一些前辈的代码及注释,可能有些地方理解的不对。如果有误,欢迎到我的github上提出。当然,希望可以点个星星。
node-http
Node.js提供了http模块,用于搭建HTTP服务端和客户端。
创建Web服务器
- server.js
/** * 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
。
源码地址
阅读全文
0 0
- Nodejs http、url模块
- nodejs模块-http
- nodejs http模块
- nodejs的HTTP模块
- nodejs HTTP模块SuperAgent
- NodeJS http模块
- nodejs http网络模块
- 大话NodeJS之------Http模块
- 02-nodejs之http模块
- NodeJS学习笔记之Http模块
- nodejs开发——http模块
- NodeJS的核心模块http服务器端
- nodejs核心模块-http path url querystring
- nodejs与golang的http模块性能对比
- nodejs-使用request和bluebird编写的http请求模块
- nodejs如何请求路由,http和url模块
- NodeJS HTTP模块编写POST提交表单Demo
- nodejs模块:简单http请求路由,仿express
- JAVA八大基本数据类型及Scanner用法
- oracle用户创建及权限设置
- Java对象的序列化和反序列化
- Android开发-文件重命名
- python的httplib、urllib和urllib2的区别及用
- NodeJS http模块
- 京东编程题(OJ输入输出)
- Win下最爱效率神器:AutoHotKey
- hibernate工作原理(非底层原理)
- QwtPlot之绘制统计图
- django--URL配置
- Hibernate一对多双向关联映射
- 猜数字 HDU
- CelebA数据库转换为VOC、YOLO格式