封裝一個類似express架構的路由
首先 建立一個檔案夾 router.js
//首先引入url子產品
const url = require('url')
//建立一個箭頭函數
let server = () => {
let G = {}; //定一個全局變量
G._get = {}; //在變量中添加一個靜态方法get,post
G._post = {};
let app = function (req, res) {
let pathname = url.parse(req.url).pathname;
// 擷取請求類型
let method = req.method.toLowerCase();
if (G['_'+method][pathname]) { //G._get.['/login']
if (method == 'get') {
G['_'+method][pathname](req, res)
}else{
let postData='' //建立資料變量
req.on('data',(chunk)=>{ //接收post請求的資料
postData +=chunk
})
req.on('end',()=>{
req.body=postData //req.body接收post請求傳來的資料 req.query接收get請求傳來的資料
G['_'+method][pathname](req, res) //執行G._post['/login']的方法,也就是 app.post
})
}
} else {
res.writeHead(404, { 'Content-Type': 'text/html;charset="utf-8"' })
res.end('頁面不存在')
}
}
//建立一個post,get方法
app.get = function (str, cb) {
G._get[str] = cb
}
app.post = function (str, cb) {
G._post[str] = cb
}
//把app傳回出去
return app
}
//暴露server方法
module.exports = server()
const http = require('http')
const app = require('./route') //導入上方的類似express封裝的架構
const ejs = require('ejs') //ejs用于背景模闆,可以通過讀取檔案資訊顯示到HTMl頁面上
http.createServer(app).listen(3000) //建立一個端口
// 配置路由
app.get('/', function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/html;charset="utf-8"' });
res.end('Hello World3')
})
app.get('/login', function (req, res) {
ejs.renderFile('./view/form.ejs',{},(err,data)=>{ //使用ejs模闆 ejs.renderFile('路徑',資料,(err,data)={}) 資料 {message:'你好我是内容'}後期可以通過ejs文法填寫在html檔案中
res.writeHead(200, { 'Content-Type': 'text/html;charest="utf-8"' });
res.end(data)
})
})
app.post('/admin', function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/html;charset="utf-8"' });
res.end(req.body)
})
導入的頁面資訊,也就是在login中的form.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="/admin" method="post">
使用者名:<input type="text" name="username" />
<br> 密碼:
<input type="password" name="password">
<button type="submit">送出</button>
</form>
</body>
</html>
這樣
app
就起到一個
express
的功能