1.利用http url path fs 模块建立静态网站服务器
文件路径:demo09
所需文件
//利用http url path fs 模块建立简单服务器
//app.js
const http = require('http');
const fs = require('fs');
const path = require('path');
const url = require('url');
//建立http服务器
http.createServer((req,res)=>{
//获取文件名 url解析防止 http://127.0.0.1:3001/index.html?2313123 无法取到index.html
var nowurl= url.parse(req.url).pathname ;
//取文件后缀名 方便设置响应头
var extname = path.extname(nowurl);
var size=getExtname(extname);
//设置首页
if(nowurl=='/'){
fs.readFile('./test/index.html',(err,data)=>{
//读取文件成功
res.writeHead(200,{"Content-type":"text/html;charset='utf-8'"});
res.write(data);
res.end();
});
}
//过滤图标请求
else if(nowurl!='/favicon.ico'){
fs.readFile('./test/'+nowurl,(err,data)=>{
//不存在读取文件
if(err){
fs.readFile('./test/404.html',(err,data)=>{
//读取错误404文件
res.writeHead(200,{"Content-type":"text/html;charset='utf-8'"});
res.write(data);
res.end();
});
}else
//存在读取文件
{
res.writeHead(200,{"Content-type":size+";charset='utf-8'"});
res.write(data);
res.end();
}
});
}
}).listen(3001);// http://127.0.0.1:3001
//传入.html 输出text/html
function getExtname(extname){
//同步方法读取mime.json中的文件
var sdextname = fs.readFileSync('./mime.json');
var mimes = JSON.parse(sdextname.toString()); //将读取到的数据保存为对象
return mimes[extname];
}
2.封装静态网站服务器
文件路径:demo11
app.js
//利用http url path fs 模块建立简单服务器
const http = require('http');
const router = require('./modules/router.js');
const staticpath = './test/'; //静态文件地址
//建立http服务器
http.createServer((req,res)=>{
router.router(req,res,staticpath);
}).listen(3001);// http://127.0.0.1:3001
router.js 封装
const fs = require('fs');
const path = require('path');
const url = require('url');
//封装静态路由
exports.router=(req,res,staticpath)=>{
//获取文件名 url解析防止 http://127.0.0.1:3001/index.html?2313123 无法取到index.html
var nowurl= url.parse(req.url).pathname ;
//取文件后缀名 方便设置响应头
var extname = path.extname(nowurl);
var size=getExtname(extname);
//设置首页
if(nowurl=='/'){
fs.readFile(staticpath+'index.html',(err,data)=>{
//读取文件成功
res.writeHead(200,{"Content-type":"text/html;charset='utf-8'"});
res.write(data);
res.end();
});
}
//过滤图标请求
else if(nowurl!='/favicon.ico'){
fs.readFile(staticpath+nowurl,(err,data)=>{
//不存在读取文件
if(err){
fs.readFile('./test/404.html',(err,data)=>{
//读取错误404文件
res.writeHead(200,{"Content-type":"text/html;charset='utf-8'"});
res.write(data);
res.end();
});
}else
//存在读取文件
{
res.writeHead(200,{"Content-type":size+";charset='utf-8'"});
res.write(data);
res.end();
}
});
}
}
//传入.html 输出text/html
function getExtname(extname){
//同步方法读取mime.json中的文件
var sdextname = fs.readFileSync('./mime.json');
var mimes = JSON.parse(sdextname.toString()); //将读取到的数据保存为对象
return mimes[extname];
}
3.路由:对不同的路径访问,执行不同的业务逻辑
文件路径:demo12
const http = require('http');
const url = require('url');
//路由: 对不同的路径访问,执行不同的业务逻辑
http.createServer((req,res)=>{
//取url后参数
var pathname= url.parse(req.url).pathname;
//接受到login参数
if(pathname=='/login'){
res.end('login');
}
//接收到dologin参数
else if(pathname=='/dologin'){
res.end('dologin');
//接受到其他参数
}else{
res.end('index');
}
}).listen(3002);//http://127.0.0.1:3002
4.EJS模板引擎
文件路径:demo12
npm install ejs --save
后端数据库与前端页面进行数据交互
4.1ejs.readerFile
读取.ejs页面文件 将后台数据传入 并回调拿到页面数据
ejs.readerFile(.ejs文件地址,{要传入的数据},function(err,pagedata){})
app.js:
const http = require('http');
const url = require('url');
const ejs = require('ejs');
//路由: 对不同的路径访问,执行不同的业务逻辑
http.createServer((req,res)=>{
//取url后参数
var pathname= url.parse(req.url).pathname;
res.writeHead(200,{"Content-type":"text/html;charset='utf-8'"});
if(pathname=='/login'){
res.end('login');
}
else if(pathname=='/dologin'){
res.end('dologin');
}else{
//从数据库获取数据
var newstitle = '头条新闻';
var newslist = ['title1','title2','title3'];
//ejs 读取模板文件 (path,写入数据,回调得到页面数据)
ejs.renderFile('./views/index.ejs',{
title:newstitle,
list:newslist
},(err,data)=>{
//回调返回模板页面数据
res.end(data);
});
}
}).listen(3002);//http://127.0.0.1:3002
index.ejs:ejs文件中数据用法
<html>
<head>
<meta charset="UTF-8">
<title> <%=title%></title>
</head>
<body>
<ul>
<% for(var i=0;i<list.length;i++){%>
<ol><%=list[i]%></ol>
<%}%>
</ul>
</body>
</html>
5.get与post
文件路径:demo12
在服务器与客户端之间进行请求-响应时,经常用到的方法post,get
get:向指定资源请求数据(获取数据)
post:向指定资源提交经过处理的数据(提交数据)
get/post方式用ejs模板实现页面传参(也是服务器端拿到页面提交数据)
luyou.js
const http = require('http');
const url = require('url');
const ejs = require('ejs');
//路由: 对不同的路径访问,执行不同的业务逻辑
http.createServer((req,res)=>{
//取url后参数
var pathname= url.parse(req.url).pathname;
res.writeHead(200,{"Content-type":"text/html;charset='utf-8'"});
//get方式发送登录页面数据
if(pathname=='/getlogin'){
ejs.renderFile('./views/getlogin.ejs',{},(err,pagedata)=>{
res.end(pagedata);
});
//post方式发送登录页面数据
}else if(pathname=='/postlogin'){
ejs.renderFile('./views/postlogin.ejs',{},(err,pagedata)=>{
res.end(pagedata);
});
}
//接受数据页面
else if(pathname=='/dologin'){
//获取get 或者 post 方式
console.log(req.method);
//获取GET/POST小写字母
var method = req.method.toLowerCase();
// 由login.ejs页面以get方式传过来
if(method=='get'){
//拿到页面传参 username=123&password=222
console.log(url.parse(req.url).query);
res.write("<head><meta charset='UTF-8'/> </head>");
res.write('拿到get方式传过来的参数:');
res.end(url.parse(req.url).query);
}
// 由login.ejs页面以post方式传过来
if(method=='post'){
var postdata='';
//类似fs.readFilestream流的方式
req.on('data',(chunk)=>{
postdata +=chunk;
});
req.on('end',(err)=>{
res.write("<head><meta charset='UTF-8'/> </head>");
res.write('拿到post方式传过来的参数:');
res.end(postdata);
})
}
}else{
//从数据库获取数据
var newstitle = '头条新闻';
var newslist = ['title1','title2','title3'];
//ejs 读取模板文件 (path,写入数据,回调得到页面数据)
ejs.renderFile('./views/index.ejs',{
title:newstitle,
list:newslist
},(err,data)=>{
//回调返回模板页面数据
res.end(data);
});
}
}).listen(3002);//http://127.0.0.1:3002
postlogin.ejs
<html>
<head>
<meta charset="UTF-8">
<title> </title>
</head>
<body>
<h1>登录-post方式发送数据</h1>
// action 为发送到dologin 页面
<form action="/dologin" method="post">
<input type="text" name="username"/>
<input type="password" name="password"/>
<input type="submit" value="提交"/>
</form>
</body>
</html>
get.ejs
<html>
<head>
<meta charset="UTF-8">
<title> </title>
</head>
<body>
<h1>登录-get方式发送数据</h1>
// action 为发送到dologin 页面
<form action="/dologin" method="get">
<input type="text" name="username"/>
<input type="password" name="password"/>
<input type="submit" value="提交"/>
</form>
</body>
</html>
6.巧用定义方法
长用于封装特定函数
文件路径:demo13
//定义全局对象G
var G = {};
function app(req,res){
//如果G函数存在 就执行
if(G['login']){
G['login'](req,res);
}
}
//定义get方法
app.get=function(datastring,callback){
//注册G方法
G[datastring]=callback;
//相当于G[datastring]=function(req,res){}
}
//运行app.get()方法来定义G对象中的方法
app.get('login',function(res,req){
console.log('登录成功'+req+res);
});
//运行app()方法来检测G对象中方法是否存在 存在则执行
app('req','res');
7.巧用方法和http/url模块结合
文件路径:demo13
实现访问路径与业务逻辑的分离
//运用巧用方法结合html url模块 实现路径与业务逻辑的分离
const http=require('http');
const url = require('url');
//定义全局对象G
var G = {};
function app(req,res){
var pathname = url.parse(req.url).pathname;
//如果G函数存在 就执行
if(G[pathname]){
G[pathname](req,res);
}else{
res.end('no router');
}
}
//定义get方法
app.get=function(datastring,callback){
//注册G方法
G[datastring]=callback;
//相当于G[datastring]=function(req,res){}
}
//只要进行对端口3030的访问,就执行app()方法
http.createServer(app).listen(3030); //http://127.0.0.1:3030/login
//注册 G方法
app.get("/login",(req,res)=>{
res.end('login');
});
8.封装类express路由
文件路径:demo14
express.js
实现创建两个登录页面getlogin和postlogin以及一个接受数据的页面dologin(两张方式接收)
const url = require('url');
//改变res属性 向res 添加 res.send方法
var changeRes = function (res) {
res.send = function (data) {
res.writeHead(200, { 'Content-Type': 'text/html;charset="utf-8"' });
res.end(data)
}
}
//创建暴露的模块
var Router = function () {
//定义G对象绑定Router 相当于Router里多了个G 对象
var G = this;
//定义get post 获取数据方式 服务 相当于服务器端接收数据时的类型
this._get = {};
this._post = {};
//定义app模块
function app(req, res) {
//改变res属性 向res 添加 res.send方法
changeRes(res);
//获取访问参数
var pathname = url.parse(req.url).pathname;
//获取访问方式 get post
var method = req.method.toLowerCase();
// console.log(method);
//寻找路由是否存在
if (G['_' + method][pathname]) {
//路由存在 判断get或者post 方法
if (method == 'post') { //若为post方式
var newsdata = '';
req.on('data', (chunk) => {
newsdata += chunk;
});
req.on('end', (err, chunk) => {
req.body = newsdata; //把数据传进req.body中
G['_' + method][pathname](req, res);
});
} else { //为get方式 可在req.url.query中获取
G['_' + method][pathname](req, res);
}
} //路由不存在
else {
res.end('no router');
}
}
//定义get方式获取到的数据
app.get = function (urlname, callback) {
//注册G._get对象
G._get[urlname] = callback;
}
//定义get方式获取到的数据
app.post = function (urlname, callback) {
//注册G._post对象
G._post[urlname] = callback;
}
return app;
}
module.exports = Router();
http.js
const http = require('http');
const app = require('./router/express.js');
const ejs = require('ejs');
const url = require('url');
http.createServer(app).listen(3011);//http://127.0.0.1:3011
//注册index页面
app.get('/index', (req, res) => {
// var title = '新闻';
// var list = ['1', '2', '3'];
// ejs.renderFile('./views/index.ejs', { title, list }, (err, data) => {
// res.send(data);
// });
res.send('index');
});
//注册get方式提交数据的 getlogin页面
app.get('/getlogin', (req, res) => {
ejs.renderFile('./views/getlogin.ejs', {}, (err, data) => {
res.send(data);
});
});
//注册get方式提交数据的 dologin页面
app.get('/dologin', (req, res) => {
var newdata = url.parse(req.url).query;
var method = req.method.toLowerCase();
// console.log(method);
ejs.renderFile('./views/dologin.ejs', { newdata, method }, (err, data) => {
res.send(data);
});
});
//注册post方式提交数据的 postlogin页面
app.get('/postlogin', (req, res) => {
ejs.renderFile('./views/postlogin.ejs', {}, (err, data) => {
res.send(data);
});
});
// //注册post方式提交数据的 dologin页面 注册了两次dologin 所有第二次 用req.on 接收不到Post传过来的数据
app.post('/dologin', (req, res) => {
var newdata = req.body;
var method = req.method.toLowerCase();
ejs.renderFile('./views/dologin.ejs', { newdata: newdata, method: method }, (err, data) => {
res.send(data);
});
});