//引入相关模块
let http = require('http');
let path = require('path');
let url = require('url');
let fs = require('fs');
//添加静态自愿代码,详情看上一节
function staticRoot(staticPath, req, res) {
let pathObj = url.parse(req.url, true);
if (pathObj.pathname === '/favicon.ico') {
return;
}
if (pathObj.pathname === '/') {
pathObj.pathname += 'index.html';
}
let filePath = path.join(staticPath, pathObj.pathname);
fs.readFile(filePath, 'binary', (err, data) => {
if (err) {
res.writeHead(404, 'not found');
res.write('<h1>Not Found</h1>')
res.end()
} else {
res.writeHead(200, 'ok')
res.write(data, 'binary');
res.end()
}
})
}
//接口代码
var routes = {
'/a': function(req, res){
res.end(JSON.stringify(req.query))
},
'/b': function(req, res){
res.end('match /b')
},
'/a/c': function(req, res){
res.end('match /a/c')
},
'/search': function(req, res){
res.end('username='+req.body.username+',password='+req.body.password)
}
}
//解析请求资源
function routePath(req, res) {
//解析请求的url
let pathObj = url.parse(req.url, true);
//获取参数名称,返回函数对象
let handleFunc = routes[pathObj.pathname];
//判断routes数组中存在接口数据
if (handleFunc) {
//存在,监听data和on事件
let body = '';
req.on('data', function (chunk) {
//获取加载的数据
body += chunk;
console.log(body)
}).on('end', function () {
//加载完成,解析body
req.body = parseBody(body);
//传递参数,调用参数对象
handleFunc(req, res)
})
} else {
//不存在,则是静态资源
staticRoot(path.join(__dirname, 'static'), req, res)
}
}
//解析body参数,简单的处理
function parseBody(body){
console.log(body)
var obj = {}
body.split('&').forEach(function(str){
obj[str.split('=')[0]] = str.split('=')[1]
})
return obj
}
//创建服务
http.createServer((req, res) => {
routePath(req, res);
}).listen(8080)