路由
const http = require('http')
const router = require('./model/router')
const app = http.createServer((req, res) => {
router.statics(req, res, 'static')
})
app.listen(8000)
const fs = require('fs')
const path = require('path')
const url = require('url')
const getMime = (extname, callback = () => '无回调函数') => {
fs.readFile('./mime.json', (err, data) => {
if (err) {
console.log('mime.json文件不存在')
return
}
const Mimes = JSON.parse(data.toString())
const result = Mimes[extname] || 'txt/html'
callback(result)
})
}
exports.statics = (req, res, staticpath='static') => {
let pathname = url.parse(req.url).pathname
if (pathname === '/') {
pathname = '/index.html'
}
const extname = path.extname(pathname)
if (pathname !== '/favicon.ico') {
fs.readFile(`${staticpath}${pathname}`, (err, data) => {
if (err) {
fs.readFile(`${staticpath}/404.html`, (err, data) => {
if (err) {
console.log(err)
return
}
res.writeHead(404, {'Content-Type': 'text/html;charset="utf-8"'})
res.end(data)
})
return
}
getMime(extname, mime => {
res.writeHead(200, {'Content-Type': `${mime};charset='utf-8'`})
res.end(data)
})
})
}
}
模板引擎
const http = require('http')
const url = require('url')
const ejs = require('ejs')
const fs = require('fs')
http.createServer((req, res) => {
res.writeHead(200, {
"Content-Type": "text/html;charset='utf-8'"
})
let method = req.method.toLowerCase()
let pathname = url.parse(req.url).pathname
if (pathname === '/login') {
ejs.renderFile('views/form.ejs', {}, (err, data) => {
res.end(data)
})
} else if (pathname === '/dologin' && method === 'get') {
console.log(url.parse(req.url, true).query)
res.end('dologin get')
} else if (pathname === '/dologin' && method === 'post') {
let postStr = ''
req.on('data', (chunk) => {
postStr += chunk
})
req.on('end', (err, chunk) => {
fs.appendFile('login.txt', postStr + '\n', (err) => {
if (err) {
console.log(err)
return
}
console.log('写入数据成功')
})
res.end('<script>alert("登录成功");history.back();</script>')
})
} else {
ejs.renderFile('views/index.ejs', {}, (err, data) => {
res.end(data)
})
}
}).listen(8000)
<%=msg%> // 读取值
<%-h%> // 把变量h字符串不转义
<% for(let i=0; i<list.length;i++) {%>
<h2><%=list[i]%></h2>
<% } %>