如果看不懂,可以移步我往期的博客地址
express-router.js
//引入相应模块
const http = require('http')
const ejs = require('ejs')
var app = require('./module/router-ww')
//创建web服务器
//每次请求时触发调用app函数,先寻找静态目录,没有就触发调用相应的路由
http.createServer(app).listen(3000)
//修改静态Web目录
app.staticPath('public')
//配置路由
app.get('/',(req,res) =>{
res.send('首页')
})
app.get('/login',(req,res) =>{
ejs.renderFile('./views/form.ejs', {},(err, str)=>{
// str => Rendered HTML string
res.send(str)
});
})
app.post('/dologin',(req,res) =>{
console.log(res.body)
res.send(res.body)
})
app.get('/news',(req,res) =>{
res.send('新闻界面')
})
console.log('Server running at http://127.0.0.1:3000/')
router-ww.js
//引入相应模块
const url = require('url')
const path = require('path')
const fs = require('fs')
//扩展方法方法 设置响应数据
let changeRes = (res) =>{
res.send = (data) => {
res.writeHead(200,{"Content-Type":"text/html;charset='utf-8'"})
res.write("<head><meta charset='UTF-8'></head>")
res.end(data)
}
}
//根据后缀名获取文件类型
let getFileMimeSync = (extname)=> {
var data = fs.readFileSync('./data/mime.json')
let mimeObj = JSON.parse(data.toString())
return mimeObj[extname]
}
//静态Web服务
let createStaticWebServer = (req,res,staticPath) =>{
//获取请求地址
let pathname = url.parse(req.url).pathname
//获取地址后缀名
let ext = path.extname(pathname)
// console.log(url.parse(req.url))
try {
//为防止路由的检索先执行,故应该使用文件的读取的同步方法
var data = fs.readFileSync('./'+staticPath+pathname)
if (data){
//根据后缀类型设置对应的响应头部
res.writeHead(200,{"Content-Type":`${getFileMimeSync(ext)};charset='utf-8'`})
res.end(data)
}
}catch (e) {
// console.log(e)
}
}
let Server = () => {
let G = {
_get:{}, //get路由
_post:{}, //post路由
staticPath: 'static', //默认静态Web目录
}
let app = function (req,res) {
//扩展res的方法
changeRes(res)
//配置静态Web服务
createStaticWebServer(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传值
let postData = ""
req.on('data',(chunk)=> {
postData += chunk
})
req.on('end',() => {
res.body = postData
G._post[pathname](req,res)
})
}
}else{
res.send('页面不存在')
}
}
//get
app.get = function(string,cb){
//注册方法
G._get[string] = cb
//在express-router.js中配置路由的时候执行,就相当于声明一个函数
}
//post
app.post = function (string,cb) {
G._post[string] = cb
}
//静态目录
app.staticPath = function (staticPath) {
G.staticPath = staticPath
}
return app
}
//向外暴露
module.exports = Server()
./data/mime.json
./views/form.ejs
./css/style.css