一、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//..'));
// fooarazfile01
// 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字符串。
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 {
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;
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;
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>
结果: