使用express框架可以结合中间件body-parser方便处理前端发送过来的数据。(class10)
第一部分:
1.新建目录后,打开cmd---进入当前目录---cnpm install express express-static body-parser
2.目录结构:
3.10index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>10 body-parser 中间件使用</title>
</head>
<body>
<form action="http://localhost:8087/user" method="post">
<input type="text" name="username" id="u">
<input type="text" name="psw" id="psw" >
<input type="button" onclick="register()" value="register">
<input type="button" onclick="login()" value="login">
</form>
<script src="https://cdn.bootcss.com/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
const log = console.log;
let eUsename = document.getElementById("u");
let ePsw = document.getElementById("psw");
function register(){
$.ajax({
type:"post",
data:{"action":"register","username":eUsename.value,"psw":ePsw.value},
url:"/user",
success:function(data){ // 后台用body-parser中间件处理过json,直接返回的data也不用eval处理了,否则会报错
log("json=",data)
},
error:function(err){
log("err=",err);
}
})
}
function login(){
$.ajax({
type:"post",
data:{"action":"login","username":eUsename.value,"psw":ePsw.value},
url:"/user",
success:function(data){ // 后台用body-parser中间件处理过json,直接返回的data也不用eval处理了,否则会报错
log("json=",data)
},
error:function(err){
log("err=",err);
}
})
}
</script>
</body>
</html>
4.10s.js
const log = console.log;
const express = require("express") // nodejs 框架
const expressStatic = require("express-static") //处理前端静态页面
const bodyParser = require("body-parser") // 处理前端post过来的数据
const server = express(); // 创建服务
server.listen(8087)
server.use(bodyParser.urlencoded({ //这是一个中间件,有两个参数
extended: false, // 扩展,很少用
limit: 1024 * 1024 * 2 // 前端最大可提交数据限制
}));
/** 接口设置 http://localhost:8087/user?action=register&username=tcc&psw=123
接口设置 http://localhost:8087/user?action=login&username=tcc&psw=123
* */
let users = {}; // 现在我们没有数据库,所以定义一个对象来存储用户的信息.
server.post("/user",function(req,res,next){
let params = req.body;
if(params.action == "register"){
if(users[params.username]){
res.write({"status":false,msg:"用户已经存在!"}) //res.write也是一样的
}else{
users[params.username] = params.psw
res.send({"status":true,msg:"注册成功!"})
}
}else if(params.action == "login"){
if(!users[params.username]){
res.send({"status":false,msg:"用户名不正确!"})
}else if(users[params.username] == params.psw){
res.send({"status":true,msg:"登录成功!"})
}else{
res.send({"status":false,msg:"登录失败!"})
}
}else{
res.send("no register login")
}
res.end(); // 告诉浏览器,响应结束
})
server.use(expressStatic("./www")) // 处理静态资源,http://localhost:8087/10index.html 成功访问www/10index.html
以上示例就是使用body-parser专门处理前端post过来的数据。
第二部分:自定义中间件middleware原理:写中间件,要明白只有相同的请求才能算是同一条线程上,req更改的值在next()后方能正确传递下去
/** 第一种写法*/ server.use(function (req, res, next) { //所有请求都可访问 req.on('data', function (data) { }) req.on('end', function () { req.tcc = "tcc"; // 当next() 执行后,把tcc传递给后面的req //res.end(); 不能在这里结束,后面还要运行 next(); // next()不能写在 res.end()后面 }) }) server.use("/user", function (req, res, next) { // 只有localhost:8087/user 可以访问 req.on('data', function (data) { }) req.on('end', function () { log('req.tcc=', req.tcc) // 能取到上一个访问传下来的tcc log(2) }) })
/***
* 第二种写法,第二个server.use里直接取req.body,不再通过req.on("end",function(){})
* */
server.use(function(req,res,next){ // 能接收所有访问,与/user也就在同一条线上了
let str = "";
req.on("data",function(data){
str +=data;
})
req.on("end",function () {
req.tcc = querystring.parse(str); //
next(); // 正确执行
})
})
server.use("/user",function(req,res,next){ // 只有localhost:8087/user 可以访问
log('req.tcc=',req.tcc) // 取到上一个访问传下来的tcc
log(2);
res.end();
})
比较一下,基于第一部分的更改
...略......略......略......略......略......略......略......略......略......略......略...
server.listen(8087)
// server.use(bodyParser.urlencoded({ //这是一个中间件,有两个参数
// extend: false,
// limit: 1024 * 1024 * 2 // 前端最大可提交数据限制
// }));
server.use(function(req,res,next){ // 能接收所有访问,与/user也就在同一条线上了
let str = "";
req.on("data",function(data){
str +=data;
})
req.on("end",function () {
req.body = querystring.parse(str); //querystring 引入的模块const querystring = require("querystring")。
log('req.body =',req.body )
next();
})
})
/** 接口设置 http://localhost:8087/user?action=register&username=tcc&psw=123
接口设置 http://localhost:8087/user?action=login&username=tcc&psw=123
* */
let users = {}; // 现在我们没有数据库,所以定义一个对象来存储用户的信息.
server.post("/user",function(req,res,next){
let params = req.body; // 可以取到上面req.body设置的值
...略......略......略......略......略......略......略......略......略......略......略...
中间件的完整示例:
1.目录结构
2.10index.html没变,和上面的一样
3.10s.js
const log = console.log;
const express = require("express") // nodejs 框架
const expressStatic = require("express-static") //处理前端静态页面
// const bodyParser = require("body-parser") // 处理前端post过来的数据
const customMiddleware = require("./customMiddleware.js") // 自定义的中间件
const server = express(); // 创建服务
server.listen(8087)
// server.use(bodyParser.urlencoded({ // 这是一个中间件,有两个参数
// extend: false,
// limit: 1024 * 1024 * 2 // 前端最大可提交数据限制
// }));
server.use(customMiddleware.handlePostdata()) // 使用自己写的中间件
// server.use(function(req,res,next){ // 能接收所有访问,与/user也就在同一条线上了
// let str = "";
// req.on("data",function(data){
// str +=data;
// })
// req.on("end",function () {
// req.body = querystring.parse(str);
// // res.end();
//
// next();
// })
// })
/** 接口设置 http://localhost:8087/user?action=register&username=tcc&psw=123
接口设置 http://localhost:8087/user?action=login&username=tcc&psw=123
* */
let users = {}; // 现在我们没有数据库,所以定义一个对象来存储用户的信息.
server.post("/user",function(req,res,next){
let params = req.body;
log('22 req.body =',req.body )
if(params.action == "register"){
if(users[params.username]){
res.write({"status":false,msg:"用户已经存在!"}) //res.write也是一样的
}else{
users[params.username] = params.psw
res.send({"status":true,msg:"注册成功!"})
}
}else if(params.action == "login"){
if(!users[params.username]){
res.send({"status":false,msg:"用户名不正确!"})
}else if(users[params.username] == params.psw){
res.send({"status":true,msg:"登录成功!"})
}else{
res.send({"status":false,msg:"登录失败!"})
}
}else{
res.send("no register login")
}
res.end(); // 告诉浏览器,响应结束
})
server.use(expressStatic("./www")) // 处理静态资源,http://localhost:8087/10index.html 成功访问www/10index.html
Brief summary:
先看要require哪些模块,按步骤轻松掌握如何处理post数据,并且学会如何写一些中间件middleware.
努力学习!加油!^_^