此例实现的功能如下图所示
计算结果
代码如下
app-node.js
var http_port = 8124;
var http = require('http');
var htutil = require('./htutil');
function onRequest(req, res)
{
htutil.loadParams(req, res, undefined);
if(req.requrl.pathname==='/')
{
require('./home-node').get(req,res);
}
else if(req.requrl.pathname==='/square')
{
require('./square-node').get(req,res);
}
else if(req.requrl.pathname==='/mult')
{
require('./mult-node').get(req,res);
}
else
{
res.writeHead(404,{'Content-Type':'text/plain'});
res.end("bad URL"+req.url);
}
}
var server = http.createServer(onRequest);
server.listen(http_port);
console.log('listening to http://localhost:8124');
var url = require('url');
exports.loadParams = function(req,res,next)
{
req.requrl=url.parse(req.url,true);
req.a=(req.requrl.query.a && !isNaN(req.requrl.query.a))
?new Number(req.requrl.query.a):NaN;
req.b=(req.requrl.query.b && ! isNaN(req.requrl.query.b))
?new Number(req.requrl.query.b):NaN;
if(next) next();
}
//导航条
exports.navbar=function()
{
return ["{title} ",
"[title]
",
"",
"{navbar} {content} ",
"
"
].join('\n')
.replace("{title}", title,"g")
.replace("[title]", title,"g")
.replace("{navbar}", navbar, "g")
.replace("{content}", content, "g");
}
"].join('\n');
}
exports.page=function(title, navbar, content)
{
return ["
var htutil = require('./htutil');
exports.get = function(req, res)
{
res.writeHead(200, {'Content-Type':'text/html'});
res.end(
htutil.page("Math Wizard",
htutil.navbar(),
"Math Wizard
")
);
}
var htutil=require('./htutil');
exports.get=function(req, res)
{
res.writeHead(200,{'Content-Type':'text/html'});
var result=req.a*req.b;
var strT="{a}*{b}={result}
";
strT=strT.replace("{a}", req.a);
strT=strT.replace("{b}", req.b);
strT=strT.replace("{result}", result);
var resultStr=(!isNaN(req.a)&&!isNaN(req.b))?strT:"";
res.end(
htutil.page("Multiplication", htutil.navbar(),
[resultStr,
"Enter numbers to multiply
",
""].join('\n')
)
);
}
square-node.js
var htutil = require('./htutil');
exports.get = function(req, res) {
res.writeHead(200, {
'Content-Type': 'text/html'
});
res.end(
htutil.page("Square", htutil.navbar(), [
(!isNaN(req.a) ?
("{a} squared = {sq}
"
.replace("{a}", req.a)
.replace("{sq}", req.a*req.a))
: ""),
"Enter a number to see its square
",
""
].join('\n'))
);
}