一、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. jQuery多次选中checkbox失效

    在做项目的过程中,遇到一个问题.就是使用jquery的attr方法即 $("#aaa").attr('checked',true); $("#aaa").att ...

  2. js获取当前日期和时间的代码

    最佳答案 var myDate = new Date(); myDate.toLocaleDateString(): //获取当前日期myDate.toLocaleTimeString(); //获取 ...

  3. (转) AJAX POST&跨域 解决方案 - CORS

    跨域是我在日常面试中经常会问到的问题,这词在前端界出现的频率不低,主要原因还是由于安全限制(同源策略, 即JavaScript或Cookie只能访问同域下的内容),因为我们在日常的项目开发时会不可避免 ...

  4. Codeforces Round #413 B. T-shirt buying

    B. T-shirt buying time limit per test   3 seconds memory limit per test   256 megabytes   A new pack ...

  5. python基础(二)--多值参数以及类

    1.多值参数函数 def 函数名(*args , **kwargs): ....... 多值参数函数顾名思义能够传入多个参数,args表示传入的元组,kwargs表示传入的字典 def functio ...

  6. androidcode

    package UICtrl; import android.animation.ObjectAnimator;import android.content.Context;import androi ...

  7. 在 Linux 中使用 Azure Premium 存储的基本优化指南

    Note 以下测试和结果都是基于 CentOS 6.5.对于其他版本,请参考本文档,并自行进行相关测试. 建议使用最新的内核版本 一般情况下,新的内核版本能解决老版本中存在的问题,添加对新出现硬件的支 ...

  8. C++ 无名对象

    http://blog.sina.com.cn/s/blog_5f0e13360100bxlj.html 可以直接调用构造函数产生无名对象. 例如,下面的代码在函数fn()中,创建了一个无名对象: c ...

  9. 【Leetcode】【Easy】Path Sum

    Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all ...

  10. TB5上正常使用msfconsole

    在TB上使用系统自带的msfconsole,给出以下错误 [-] Failed to connect to the database: could not connect to server: Con ...