const url = require('url')
const changeRes = (res) => {
res.send = (data) => {
res.writeHead(200, {
"Content-Type": "text/html;charset='utf-8'"
})
res.end(data)
}
}
const Server = () => {
const G = this
this._get = {}
this._post = {}
const app = (req, res) => {
changeRes(res)
let pathname = url.parse(req.url).pathname
if (!pathname.endsWith('/')) {
pathname = pathname + '/'
}
let method = req.method.toLowerCase()
if (G['_' + method][pathname]) {
if (method == 'post') {
let postStr = ''
req.on('data', (chunk) => {
postStr += chunk
})
req.on('end', (err, chunk) => {
req.body = postStr
G['_' + method][pathname](req, res)
})
} else {
G['_' + method][pathname](req, res)
}
} else {
res.end('no router')
}
}
app.get = (string, callback) => {
if (!string.endsWith('/')) {
string = string + '/'
}
if (!string.startsWith('/')) {
string = '/' + string
}
G._get[string] = callback
}
app.post = (string, callback) => {
if (!string.endsWith('/')) {
string = string + '/'
}
if (!string.startsWith('/')) {
string = '/' + string
}
G._post[string] = callback
}
return app
}
module.exports = Server()
const http = require('http')
const ejs = require('ejs')
const app = require('./model/express_route.js')
console.log(app)
http.createServer(app).listen(8000)
app.get('/', (req, res) => {
let msg = '这是数据库的数据'
ejs.renderFile('views/index.ejs', {
msg
}, (err, data) => {
res.send(data)
})
})