用http模块+URI模块+Path模块+Fs模块创建一个静态web服务器。
./module/common
const fs =require(‘fs‘)
exports.getFileMime = function (extname) {
return new Promise((resolve, reject)=> {
// 读取文件 mime里面有常用类型
// 这里也可以通过readFileSync 同步方法读取
fs.readFile(‘./mime.json‘, (err, data)=>{
if (err) {
reject(err)
return
}
// json解析对象
let mime = JSON.parse(data.toString())
// 返回content-type类型
resolve(mime[extname])
})
})
}
app.js
const http = require(‘http‘);
const fs = require(‘fs‘);
// 获取后缀名
const path = require(‘path‘);
const common = require(‘./module/common‘);
const url = require(‘url‘)
http.createServer(function (request, response){
// 打印 请求url
console.log(request.url);
// 获取地址
let pathName = url.parse(request.url).pathname;
pathName = pathName === ‘/‘ ? ‘/index.html‘: pathName;
// 通过path模块获取后缀名
let extname = path.extname(pathName)
// 通过fs模块读取文件
if (pathName !== ‘favicon.ico‘) {
fs.readFile(‘./static‘ + pathName, async (err, data)=>{
if (err) {
console.log(‘404‘)
response.writeHead(404, {‘Content-Type‘: ‘text/html;charset="utf-8"‘})
response.end(‘这个页面不存在‘);
}
let mime = await common.getFileMime(extname)
response.writeHead(200, {‘Content-Type‘: `${mime};charset="utf-8"`})
response.end(data);
})
}
// // 设置响应头
// response.writeHead(200, {‘Content-Type‘: ‘text/plain;charset="utf-8"‘});
// // 设置响应内容
// response.end(‘Hello world‘);
}).listen(8081);
console.log(‘server run at http://127.0.0.1:8081/‘)
路由
是由一个URI和一个特定HTTP方法(GET,POST)组成,涉及到应用如何响应客户端对某个网站节点的访问。
EJS引擎
可以把我们数据库和文件读取的数据显示到HTML页面上,它是一个第三方模块,需要通过npm安装。
安装
npm install ejs --save
nodejs使用
ejs.renderFile(filename, data, options, function(err, str){
})
目录结构
project
|__module
| |__router.js
|__node_modules
|__static
| |__img
| | |__timg.jpeg
| |__js
| | |___htmljs.js
| |__index.html
| |__login.html
|__views
| |__form.ejs
| |__login.ejs
|__app.js
|__mime.json
app.js
const http = require(‘http‘);
const routes = require(‘./module/router‘)
const url = require(‘url‘);
http.createServer(function (request, response){
// 创建静态web服务
routes.static(request,response,‘static‘)
// 路由
let pathname = url.parse(request.url).pathname.replace("/","");
// 获取请求方式
console.log(pathname)
try {
routes[pathname](request,response);
} catch (error) {
routes[‘error‘](request,response);
}
}).listen(8081);
console.log(‘server run at http://127.0.0.1:8081/‘)
Route.js
const fs = require(‘fs‘);
// 获取后缀名
const path = require(‘path‘);
const url = require(‘url‘);
const ejs = require(‘ejs‘);
// 同步方法
let getFileNameSync = function (extname) {
var data = fs.readFileSync(‘./mime.json‘);
let mimeObj = JSON.parse(data.toString());
return mimeObj[extname]
}
let app = {
static: (request,response, staticpath)=> {
// 获取地址
let pathName = url.parse(request.url).pathname;
pathName = pathName === ‘/‘ ? ‘/index.html‘: pathName;
// 通过path模块获取后缀名
let extname = path.extname(pathName)
// 通过fs模块读取文件
if (pathName !== ‘favicon.ico‘) {
try {
let data = fs.readFileSync(‘./‘ + staticpath + pathName);
if (data) {
let mime = getFileNameSync(extname);
response.writeHead(200, {‘Content-Type‘: `${mime};charset="utf-8"`})
response.end(data)
}
} catch (error) {
}
}
},
login: (req,res)=> {
ejs.renderFile(‘./views/form.ejs‘,{},(err,data)=>{
res.writeHead(200, {‘Content-Type‘: ‘text/html;charset="utf-8"‘});
res.end(data)
})
},
news: (req,res)=> {
res.end(‘news‘)
},
doLogin:(req,res)=> {
// post请求获取数据
var postData = ‘‘;
req.on(‘data‘,(chunk => {
// 将post请求数据拼接
postData += chunk;
}))
req.on(‘end‘,()=>{
console.log(postData);
res.end(postData)
})
}, error: (req, res)=> {
res.end(‘error‘)
}
}
// 对外暴漏app
module.exports = app
项目目录
express-demo
|__modules
| |__routers.js
|__node_modules
|__static
| |__css
| |__mycss.css
|__views
| |__form.ejs
|__express_router.js
|__mime.json
|__package.json
module/routers.js
const path = require(‘path‘);
const url = require(‘url‘);
const fs = require(‘fs‘);
// response封装
function changeRes(response){
response.send=(data)=>{
response.writeHead(200, {‘Content-Type‘: ‘text/html;charset="utf-8"‘})
response.end(data)
}
}
// 根据后缀名获取文件类型
function getFileNameSync (extname) {
var data = fs.readFileSync(‘./mime.json‘);
let mimeObj = JSON.parse(data.toString());
return mimeObj[extname]
}
// 静态web服务的方法
function initstatic(request,response, staticpath){
// 获取地址
let pathName = url.parse(request.url).pathname;
console.log(pathName)
pathName = pathName === ‘/‘ ? ‘/index.html‘: pathName;
// 通过path模块获取后缀名
let extname = path.extname(pathName)
// 通过fs模块读取文件
try {
let data = fs.readFileSync(‘./‘ + staticpath + pathName);
if (data) {
let mime = getFileNameSync(extname);
response.writeHead(200, {‘Content-Type‘: `${mime};charset="utf-8"`})
response.end(data)
}
} catch (error) {
}
}
// 内部封装
let server = () => {
let G={
_get: {},
_post: {},
// 静态web目录
staticPath:‘static‘
};
// // 把get与post分开
// G._get = {};
// G._post = {};
let app = function (req,res) {
console.log(‘调用app方法‘)
// 将response的方法扩展
changeRes(res)
// 配置静态web服务
initstatic(req,res,G.staticPath)
// 获取路径
let pathname = url.parse(req.url).pathname;
// 获取请求方法
let method = req.method.toLowerCase()
// 执行方法
if(G[‘_‘ + method][pathname]) {
if (method === ‘get‘){
G._get[pathname](req,res);
}else{
// post方法, 获取post数据,把它绑定req.body
let postData = ‘‘;
req.on(‘data‘,(chunk)=>{
postData += chunk;
})
req.on("end",()=>{
req.body = postData;
G._post[pathname](req,res);
})
}
} else {
res.writeHead(404, {‘Content-Type‘: ‘text/html;charset="utf-8"‘})
res.end("页面不存在")
}
}
// 配置get
app.get=function (str,callback) {
console.log(‘get方法‘)
// 注册方法
G._get[str] = callback;
}
// 配置post
app.post=function (str,callback) {
G._post[str] = callback;
}
// 配置静态web服务目录
app.static=function (staticPath){
G.staticPath = staticPath;
}
return app
}
module.exports = server();
express_rouuter.js
const http = require("http");
const app = require(‘./module/routers‘)
const ejs = require(‘ejs‘)
// 注册web服务
http.createServer(app).listen(8888)
// 修改默认静态web目录
app.static(‘static‘)
console.log("Server running at http://127.0.0.1:8888/")
// 配置路由
app.get(‘/login‘,function (request,response){
ejs.renderFile(‘./views/form.ejs‘,{},(err,data)=>{
response.send(data)
})
})
app.get(‘/news‘,function (request,response){
response.send("hello world, news")
})
app.get(‘/‘,function (request,response){
response.send("hello world, 首页")
})
app.post(‘/login‘,function (request,response){
// 获取表单数据
response.send(request.body)
})
form.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>post login</title>
<link rel="stylesheet" href="/css/mycss.css">
</head>
<body>
<h2>登陆页面</h2>
<div>
<form action="/login" method="post">
用户名:<input type="text" name="username">
密码:<input type="password" name="password">
<br>
<input type="submit" value="提交">
</form>
</div>
</body>
</html>
原文:https://www.cnblogs.com/xujunkai/p/13698178.html