一、http模块

const http = require('http');
http.createServer((req,res)=>{
//1 设置响应头
res.writeHead(200,{'content-type': 'text/html; charset=utf-8'}); // 2 设置响应内容
res.write('<h1>there is a way</h1>');
res.end('<h2>always like this!</h2>') }).listen(3000,'127.0.0.1');

get 请求:

const http = require('http');
const url = require('url');
const util = require('util');
http.createServer((req,res)=>{
// 1 设置响应头
res.writeHead(200,{'content-type': 'text/html; charset=utf-8'});
// 2. 利用url模块去解析客户端发送过来的URL
res.write(req.url);
res.write('--------------------------')
res.write(util.inspect(url.parse(req.url,true)));
res.end();
}).listen(3000,'127.0.0.1'); /*
访问:http://localhost:3000/getName&a=123&b=456
结果页面显示:
/getName&a=123&b=456
--------------------------
Url { protocol: null, slashes: null, auth: null, host: null, port: null, hostname: null, hash: null, search: null, query: {}, pathname: '/getName&a=123&b=456', path: '/getName&a=123&b=456', href: '/getName&a=123&b=456' }
* */

post请求:

/*const http = require('http');
http.createServer((req,res)=>{
//1 设置响应头
res.writeHead(200,{'content-type': 'text/html; charset=utf-8'}); // 2 设置响应内容
res.write('<h1>there is a way</h1>');
res.end('<h2>always like this!</h2>') }).listen(3000,'127.0.0.1');*/ /*
const http = require('http');
const url = require('url');
const util = require('util');
http.createServer((req,res)=>{
// 1 设置响应头
res.writeHead(200,{'content-type': 'text/html; charset=utf-8'});
// 2. 利用url模块去解析客户端发送过来的URL
res.write(req.url);
res.write('--------------------------')
res.write(util.inspect(url.parse(req.url,true)));
res.end();
}).listen(3000,'127.0.0.1'); /!*
访问:http://localhost:3000/getName&a=123&b=456
结果页面显示:
/getName&a=123&b=456
--------------------------
Url { protocol: null, slashes: null, auth: null, host: null, port: null, hostname: null, hash: null, search: null, query: {}, pathname: '/getName&a=123&b=456', path: '/getName&a=123&b=456', href: '/getName&a=123&b=456' }
* *!/*/ const http = require('http');
const url = require('url');
const util = require('util');
const querystring = require('querystring'); http.createServer((req, res)=>{
let postData = '';
// 监听post 过来数据,然后存入到 postData 里
req.on('data', (chunk)=>{
postData += chunk;
});
req.on('end', ()=>{
console.log(postData);
// parse这个方法是将一个字符串反序列化为一个对象。
// 可以将user=gudon&pwd=123456 反序列化为 { user: 'gudon', pwd: '123456' }
postData = querystring.parse(postData);
//util.inspect()将任意对象转换为字符串的方法,通常用于调试和错误输出。
res.end(util.inspect(postData));
});
}).listen(3000, '127.0.0.1'); // 访问:html端post表单提交 username gudon,password为123456
// 服务端打印:user=gudon&pwd=123456
// 浏览器:{ user: 'gudon', pwd: '123456' }
// path.normalize() 输出规范格式的path字符串。
let path = require('path')
console.log(path.normalize('/foo/bar//baz/file01/file02//..'));
// \foo\bar\baz\file01
// path.extname() 获取扩展名的
// 如果 path 的最后一部分没有 . 或 path 的文件名的第一个字符是 .,则返回一个空字符串。
/*
path.extname('index.html');
// 返回: '.html'
path.extname('/etc/a/index.html');
// 返回: '.html'
path.extname('index.coffee.md');
// 返回: '.md'
path.extname('index.');
// 返回: '.'
path.extname('index');
// 返回: ''
path.extname('.index');
// 返回: ''
*/

访问服务器上文件资源的原理:

let http = require('http');
let fs = require('fs');
let path = require('path');
let url = require('url'); // 1 创建服务器
http.createServer((req,res)=>{
// 1.1 获取url 路径
let pathUrl = url.parse(req.url);
let pathName = pathUrl.pathname; // 1.2 处理路径
if(pathName.lastIndexOf('.') === -1){ // 没有点,就拼接上 index.html
pathName += '/index.html';
console.log(111);
console.log(pathName);
} let fileUrl = './' + path.normalize(pathName);
// 取出文件的后缀
let extName = path.extname(fileUrl);
console.log('扩展名',extName); // 1.3 读取文件
fs.readFile(fileUrl,(err,data)=>{
// 1.3.1 do not find the file
if (err){
res.writeHead(404, {'content-type': 'text/html; charset=utf-8'});
res.end('<h1>404, 当前页面找不到!</h1>');
} // 1.3.3 find the file
getContentType(extName,(contentType)=>{
res.writeHead(200,{'content-type': contentType});
// res.end(data);
res.end('111');
})
})
}).listen(3000); /*
获取 contentType
就是获取那个文件的类型,返回给浏览器端,浏览器的头部文件里,会对你访问的文件类型有所描述
mime.json 文件,设置了各种 文件对应的类型,如: ".jpg":"image/jpeg" 等。
*/
let getContentType = (extName,callBack)=>{
// read file
fs.readFile('./mime.json',(err,data)=>{
if (err){
throw err;
return;
} let mineJson = JSON.parse(data);
let contentType = mineJson[extName] || 'text/plain';
callBack(contentType);
})
};

未完待续。。。

二、ejs模板

  • "E" 代表 "effective",即【高效】。EJS 是一套简单的模板语言,帮你利用普通的 JavaScript 代码生成 HTML 页面。

  • EJS是一个JavaScript模板库,用来从JSON数据中生成HTML字符串。

  • https://ejs.bootcss.com/

view/data.json

{
"lists":[
{"title": "降龙十八掌", "count": 475593, "up": 1},
{"title": "诺贝尔文学奖取消", "count": 434434, "up": 1},
{"title": "加拿大大使馆丑闻", "count": 423323, "up": 0},
{"title": "今天的天气很好", "count": 346767, "up": 0},
{"title": "停车杆砸人致死", "count": 336237, "up": 1},
{"title": "this is the right way", "count": 325193, "up": 0},
{"title": "夏威夷火山大爆发", "count": 275593, "up": 0}
],
"source": "百度风云榜 - 实时热点"
}

server.js

let http = require('http');
let fs = require('fs');
let ejs = require('ejs'); // 1 创建服务器
http.createServer((req,res)=>{
// 1.1 读取数据
getDataJson((jsonData)=>{
// 1.2 读取模板信息
fs.readFile('./view/list.ejs',(err,data)=>{
let ejsList = data.toString(); // 1.3 实例化模板
let tmp = ejs.render(ejsList,jsonData); // 1.4 返回界面
res.writeHead(200, {'Content-Type': 'text/html;charset=utf-8'});
res.end(tmp);
}) });
}).listen(3000); let getDataJson = (callBack)=>{
fs.readFile('./model/data.json',(err,data)=>{
if(!err){
let jsonData = JSON.parse(data);
callBack(jsonData);
}else {
throw err;
}
})
}

list.ejs

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>百度风云排行版</title>
<style>
* {
margin: 0;
padding: 0;
list-style: none;
} #panel {
width: 500px;
border: 1px solid #c6c8ca;
margin: 100px auto;
} #panel_header {
display: flex;
justify-content: space-around;
border-bottom: 1px solid #ccc;
line-height: 44px;
color: #777;
} #panel_body > li {
display: flex;
flex-direction: row;
justify-content: space-between;
line-height: 44px;
border-bottom: 1px solid #e8e8e8;
} .c-icon {
background: url(https://ss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3K/r/www/cache/static/protocol/https/global/img/icons_5859e57.png) no-repeat 0 0;
display: inline-block;
width: 14px;
height: 14px;
vertical-align: text-bottom;
font-style: normal;
overflow: hidden;
} .opr-toplist-st {
margin-bottom: 2px;
} .c-icon-up {
background-position: -720px -168px;
} .c-icon-down {
background-position: -744px -168px;
} .left{
margin-left: 10px;
display: flex;
flex-direction: row;
align-items: center;
} .left .no{
display: flex;
justify-content: center;
align-items: center;
width: 18px;
height: 18px;
background-color: red;
color: #fff;
margin: 5px;
} .right{
margin-right: 10px;
} #panel_footer{
display: flex;
justify-content: flex-end;
margin: 10px;
color: #777;
font-size: 15px;
}
</style>
</head>
<body>
<section id="panel">
<div id="panel_header">
<span>排名</span>
<span>搜索指数</span>
</div>
<ul id="panel_body">
<%for(var i=0;i<lists.length;i++){%>
<li>
<div class="left">
<span class="no" style="background-color: <%= i > 2 ? 'red':'blue'%>;"><%=i+1%></span>
<span><%=lists[i].title%></span>
</div>
<div class="right">
<span><%=lists[i].count%></span>
<%if(lists[i].up === 1){%>
<i class="opr-toplist-st c-icon c-icon-up"></i>
<%}else{%>
<i class="opr-toplist-st c-icon c-icon-down"></i>
<%}%>
</div>
</li>
<%}%>
</ul>
<div id="panel_footer">
<span style="margin-right: 5px">来源:</span>
<span><%=source%></span>
</div>
</section>
</body>
</html>

结果:

Node.js http等模块 笔记05的更多相关文章

  1. Node.js高级编程读书笔记Outline

    Motivation 世俗一把,看看前端的JavaScript究竟能做什么. 顺便检验一下自己的学习能力. Audience 想看偏后台的Java程序员关于前端JavaScript的认识的职业前端工程 ...

  2. 利用Node.js的Net模块实现一个命令行多人聊天室

    1.net模块基本API 要使用Node.js的net模块实现一个命令行聊天室,就必须先了解NET模块的API使用.NET模块API分为两大类:Server和Socket类.工厂方法. Server类 ...

  3. Node.js的Formidable模块的使用

    今天总结了下Node.js的Formidable模块的使用,下面做一些简要的说明. 1)     创建Formidable.IncomingForm对象 var form = new formidab ...

  4. Node.js入门:模块机制

    CommonJS规范      早在Netscape诞生不久后,JavaScript就一直在探索本地编程的路,Rhino是其代表产物.无奈那时服务端JavaScript走的路均是参考众多服务器端语言来 ...

  5. Node.js的net模块

    net模块提供了一个异步网络包装器,用于TCP网络编程,它包含了创建服务器和客户端的方法 创建TCP服务器 net.createServer方法 创建客户端去连接服务器 net.connect方法 简 ...

  6. JavaScript、jQuery、HTML5、Node.js实例大全-读书笔记3

    技术很多,例子很多,只好慢慢学,慢慢实践!!现在学的这本书是[JavaScript实战----JavaScript.jQuery.HTML5.Node.js实例大全] JavaScript.jQuer ...

  7. JavaScript、jQuery、HTML5、Node.js实例大全-读书笔记2

    技术很多,例子很多,只好慢慢学,慢慢实践!!现在学的这本书是[JavaScript实战----JavaScript.jQuery.HTML5.Node.js实例大全] JavaScript.jQuer ...

  8. node.js中express模块创建服务器和http模块客户端发请求

    首先下载express模块,命令行输入 npm install express 1.node.js中express模块创建服务端 在js代码同文件位置新建一个文件夹(www_root),里面存放网页文 ...

  9. node.js中ws模块创建服务端和客户端,网页WebSocket客户端

    首先下载websocket模块,命令行输入 npm install ws 1.node.js中ws模块创建服务端 // 加载node上websocket模块 ws; var ws = require( ...

随机推荐

  1. go install runtime/cgo: open /usr/local/go/pkg/darwin_amd64/runtime/cgo.a: permission denied

    在做更新时,收到下面提示: go get  github.com/astaxie/beego go install runtime/cgo: open /usr/local/go/pkg/darwin ...

  2. flask之flask-login登陆验证(一)

    这个模块能帮助我们做很多事,最常用到的是,登陆验证(验证当前用户是否已经登陆).记住我功能 一 安装 pip install flask-login 二 导入相关模块及对象并初始化 from flas ...

  3. 使用powershell 执行脚本,windows默认不允许任何脚本运行

    使用如下命令让PowerShell运行在无限制的环境之下: Set-ExecutionPolicy Unrestricted

  4. [翻译]Review——How to do Speech Recognition with Deep Learning

    原文地址:https://medium.com/@ageitgey/machine-learning-is-fun-part-6-how-to-do-speech-recognition-with-d ...

  5. HDD 机械硬盘 安装 linux(centos7)

    1. 下载 UltraISO 文件-->打开, 选中centos.iso镜像;   启动-->写入硬盘映像-->硬盘驱动器(选中u盘)写入方式(USB-HDD+v2)-->写入 ...

  6. 洛谷P1600 天天爱跑步(差分 LCA 桶)

    题意 题目链接 Sol 一步一步的来考虑 \(25 \%\):直接\(O(nm)\)的暴力 链的情况:维护两个差分数组,分别表示从左向右和从右向左的贡献, \(S_i = 1\):统计每个点的子树内有 ...

  7. web前端优化之内容优化

    前端内容优化主要有以下几条: 1.尽量减少http请求 (1)合并文件,把多个css文件合并在一起: (2)css Sprites,把css相关的background元素进行背景图绝对定位: (3)图 ...

  8. CentOS新增硬盘,重新扫描总线

    Centos 新增硬盘以后,系统不能自动进行识别. 1. 由于不知道新增硬盘挂载的位置,可以先查看现有硬盘挂载的适配器. [root@localhost ~]# ls -l /sys/block/sd ...

  9. 把连接中传的参数截取出来变成一个json对象

    获取url function test() { var url=window.location.search; if(url.indexOf("?")!=-1) { var str ...

  10. Linux下OCI环境配置

    ORACLE调用接口(Oracle Call Interface简称OCI)提供了一组可对ORACLE数据库进行存取的接口子例程(函数),通过在第三代程序设计语言(如C语言)中进行调用可达到存取ORA ...