1,模块化方式封装路由
Route.js
const staticWeb = require('./web')
const app={
static:function(req,res,staticPath){
//创建静态Web服务
staticWeb(req, res, './static')
},
index:function(req,res){
res.writeHead(200, { 'Content-Type': 'text/html;charset="utf-8"' });
res.end("<h3>Index</h3>");
},
login:function(req,res){
res.writeHead(200, { 'Content-Type': 'text/html;charset="utf-8"' });
res.end("<h3>Login</h3>");
},
doLogin:function(req,res){
res.writeHead(200, { 'Content-Type': 'text/html;charset="utf-8"' });
res.end("<h3>doLogin</h3>");
},
register:function(req,res){
req.writeHead(200, { 'Content-Type': 'text/html;charset="utf-8"' });
res.end("<h3>register</h3>");
},
error:function(req,res){
res.writeHead(200, { 'Content-Type': 'text/html;charset="utf-8"' });
res.end("<h3>error</h3>");
}
}
module.exports=app;
2,调用路由模块:
app.js
const http = require('http');
const url = require('url')
const Route = require('./Router');
http.createServer(function (request, response) {
Route.static(request,response,'./static')
let pathname = url.parse(request.url).pathname //'/login'
if (pathname == '/') {
Route.index(request,response)
}
else if(pathname=='/login'){
Route.login(request,response)
}
else if(pathname=='/register'){
Route.register(request,response)
}
else{
Route.error(request,response)
}
}).listen(8081);
console.log('Server running at http://127.0.0.1:8081/');