node.js+express制作网页计算器
环境:
主机:WIN10
express安装:
1.安装express-generator
输入命令:
npm install -g express-generator
2.安装express
输入命令:
npm install -g express
3.验证是否安装成功
输入命令:express -V
查看帮助:express --help
建立工程:
express -e calculator cd calculator && npm install
运行默认网页:
输入命令:npm start或者node ./bin/www
端口配置在/bin/www中。
可以执行加法运算。
源代码:
view/index.ejs:增加输入框
<!DOCTYPE html> <html> <head> <title><%= title %></title> <link rel='stylesheet' href='/stylesheets/style.css' /> </head> <body> <form method="post"> <p>计算器</p> <input type="text" name="num1" value=<%= numa %> /><br /> <input type="text" name="num2" value=<%= numb %> /><br /> <input type="submit" value="计算" /> <p>结果:<%= sum %></p> </form> </body> </html>
routes/index.js:对提交的数据进行计算并推送结果
var express = require('express'); var router = express.Router(); /* GET home page. */ router.get('/', function(req, res, next) { res.render('index', { title: '计算器V1.0 by jdh', numa: 0, numb: 0, sum: 0 }); }); router.post('/', function (req, res) { console.log("接收:", req.body.num1, req.body.num2); var sum = parseFloat(req.body.num1) + parseFloat(req.body.num2); console.log('sum = ',sum); res.render('index', { title: '计算器V1.0 by jdh', // numa: req.body.num1, // numb: req.body.num2 numa: req.body.num1, numb: req.body.num2, sum: sum }); }); module.exports = router;
赞 (0)