最近在看MEAN(MongoDB+Express+AngularJS+Node.js)类的书籍,通过Node.js+Express实现一个简单的登录页面。
1. 在node.js项目下安装依赖
1 2 3 4 5 6 7 8 9 10 11 12 13
| { "name": "express_login", "version": "1.0.0", "description": "", "main": "index.js", "dependencies": { "body-parser": "~1.8.1", "express": "~4.9.0" } }
|
Express中获取网络请求参数的方法
在浏览器中经常会看到两类访问方式,一种是带问号,另一种是不带问号的。如:http://localhost:3000?user=jode&age=18
或者http://localhost:3000/user/:name
。
req.params属于不带问号类型,如:http://localhost:3000/user/jode
,通过req.params.name
可以获取参数name值。
req.query属于带问号类型,不需要中间件,直接查询对应的参数,如:http://localhost:3000?user=jode&age=18
,通过req.query.user
可以获取参数user值。
req.body需要引入body-parser
中间件,此方法通常用于POST
中的参数,如:http://localhost:3000?user=jode&age=18,通过req.query.user
可以获取参数user值。
在终端输入npm install
完成安装。
2. 创建服务文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| var express = require("express"); var bodyParser = require("body-parser"); var app = express();
app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false }));
app.set('views', __dirname + '/view'); app.set('view engine', 'html');
app.listen(3000,function(){ console.log("Strated on port 3000!"); });
|
3. 构建路由
1 2 3 4 5 6 7 8 9 10 11 12
|
app.get("/",function(req,res){ res.sendFile(__dirname + "/views/index.html"); })
app.post("/login",function(req,res){ var username = req.body.user; var password = req.body.password; console.log("User name=" + username + ",password is" + password); res.end('yes'); })
|
4. 构建视图页面
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| //views/index.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title></title> <link rel="stylesheet" href=""> <link href="https://cdn.bootcss.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <form> <h4>登录演示</h4> <div class="form-group"> <label for="username">用户名</label> <input type="text" class="form-control" id="username" placeholder="用户名"> </div> <div class="form-group"> <label for="password">密码</label> <input type="password" class="form-control" id="password" placeholder="密码"> </div> <button type="button" class="btn btn-default">登录</button> </form>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script> <script type="text/javascript"> $(function(){ $(".btn-default").click(function(){ var username = $("#username").val(); var password = $("#password").val();
$.post("http://localhost:3000/login",{user: username,password: password},function(json){ if(json){ alert("Login Success!"); } }); })
}) </script> </body> </html>
|
至此,一个简单的登录演示demo完成。