1.express 认识
/*
express 是node的框架
没有新的模块儿,是原生模块的集成
需要安装 npm install express
三个功能
1.路由
2.中间件
3.模板引擎
*/
let express = require('express'); //引入模块
let app = express();
let { link } = require('./db');//引入mysql句柄和连接
/*
设置路由
*/
/*
get方法 第一个参数,访问路径,第二个方法是一个回调函数
该回调函数具有两个参数,它本质是http创建的服务器,因此req和res具有和http模块
创建服务的回调函数参数,相同的意义
*/
app.get('/',(req,res)=>{
console.log('行到水穷处');
res.send('行到水穷处');
});
// 可以直接向前台传递文件资源
app.get('/index.html',(req,res)=>{
console.log(req.path); //req.path 访问的路径
// res.send('坐看云起时');
//发送文件
// res.sendFile(__dirname+'/index.html');
res.sendFile(__dirname+req.path);
});
// 引入css
// app.get('/style.css',(req,res)=>{
// res.sendFile(__dirname+req.path);
// });
app.get('/info',(req,res)=>{
console.log(req.query); // req.query是get请求提交的数据集合对象
res.send('画鬼容易画人难'+req.query.name);
});
//注册
app.get('/reg',(req,res)=>{
let { name,age,sex,phone,email } = req.query;
//相当于
// let name = req.query.name;
// let age = req.query.age;
// let sex = req.query.sex;
// let phone = req.query.phone;
// let email = req.query.email;
// req.query = { name: name, age: age, sex: sex, }
let sql = "INSERT INTO `student`(`name`, `age`, `sex`, `phone`, `email`) VALUES ('"+name+"',"+age+","+sex+",'"+phone+"','"+email+"')";
link.query(sql,(err,results)=>{
if(err){
console.log(err);
res.send('404');
}else{
console.log(results);
res.send('操作成功');
}
});
});
// * 代表的是所有路径,
app.get('*',(req,res)=>{
res.sendFile(__dirname+req.path);
});
app.listen(8080,()=>{
console.log('服务启动成功');
});
//注册前端页面
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>主页</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<h1>大风歌</h1>
姓名: <input type="text" value="" id="username" ><br/>
年龄: <input type="text" value="" id="age" ><br/>
<button id="btn">提交</button>
<h1>注册</h1>
<div class="wp">
姓名: <input type="text" value="" id="regName" ><br/>
年龄: <input type="text" value="" id="regAge" ><br/>
性别: <label><input type="radio" checked name="sex" value="0">男</label> <label><input type="radio" name="sex" value="1">女</label><br/>
手机: <input type="text" value="" id="phone" ><br/>
邮箱: <input type="text" value="" id="email" ><br/>
<button id="regBtn">提交注册</button>
</div>
</body>
</html>
<script src="./jquery.js"></script>
<script>
$('#btn').click(function(){
$.ajax({
type:'get',
url:'/info',
data:{
name: $('#username').val(),
age: $('#age').val()
},
success(data){
console.log(data);
$('h1').html(data);
}
});
});
//点击注册
$('#regBtn').click(function(){
let obj = {
name:$('#regName').val(),
age:$('#regAge').val(),
sex:$('input[name="sex"]:checked').val(),
phone:$('#phone').val(),
email:$('#email').val()
};
// console.log(obj);
$.get('/reg',obj,data=>{
console.log(data);
});
});
</script>
2.express 中间件
/*
中间件
使用方式是 app.use(中间件)
浏览器向服务器发送请求,服务通过req获取req上的参数,由于服务器的主要作用是用来给予前台响应信息,
而非处理复杂的业务逻辑,因此需要一个函数来专门处理这些数据,这个处理数据的函数,就称为中间件
中间件的分类
1.内置中间件
express.static() 这是express中唯一内置中间件,用来处理静态资源
2.自定义中间件
中间件是一个函数,它里面的参数个数不确定
如果有两个参数 则代表 req,res
如果三个参数 则代表 req,res,next
如果有四个参数 则代表 err, req,res,next
如果中间件中有next函数参数执行,则可以直接执行中间件以后的代码,通过中间件处理的数据,也会被传递下去,这也是中间件最大的作用
3.第三方中间件
body-parser 解析body中传递的参数,并将它存储到req的body属性中
使用中间件需要注意
1.使用 app.use() 来应用一个中间件
2.中间件都有一个next函数,如果不调用next函数,中间件是无法向外部传递数据的
3.中间件的路由处理函数中具有不同数量的参数
2个: req,res
3个:req,res,next
4个:err,req,res,next
4.中间件的第一个参数可以是路由路径,如果设置了第一个参数,那么该中间件只对当前路由起作用
5.如果是非内置中间件,则需要通过外部引入方可使用,尽量不要在服务器启动文件中书写中间件
*/
module.exports = aa=>{
// 自定义的时候,需要把中间件函数整体返回
aa+='自挂东南吃';
return (req,res,next)=>{
req.query.str = aa+'一江春水向东流';
next();
}
};
2.1express内置中间件
- .use()
- 动态路由
const express = require('express');
const path = require('path');
const app = express();
const key = require('./key');
const da = require('./abc');
// app.use(da());
// 设置路径
let pa = path.join(__dirname,'../','/static');
console.log(pa);
let num = 10;
//自定义中间件,注意中间件一般写在app.get的前面
app.use('/run',(req,res,next)=>{
num+=100;
req.query.num = num;
next(); //确保数据传出当前中间件,代码会继续往下执行
});
//通过中间件,处理静态资源 express.static() 它的参数是静态资源路径
app.use(express.static(pa));
app.use(key('问君能有几多愁'));
app.use((req,res,next)=>{
req.query.num += 100;
next();
});
app.get('/fun',(req,res)=>{
let a = req.query.num;
res.send(a+'许崇智'+req.query.str);
});
app.get('/run',(req,res)=>{
let a = req.query.num;
res.send(a+'汪精卫'+req.query.str);
});
app.get('/',(req,res)=>{
num+=100;
console.log(num);
let pa = path.join(__dirname,'../');
res.sendFile(pa+'/static/index.html');
// res.send('屈原');
});
// app.get('/abc.html',(req,res)=>{
// // req.path 是访问路由 也即是第一个参数的内容
// // req.query 用get请求方式 提交的数据
// console.log(req.query);
// let pa = path.join(__dirname,'../');
// res.sendFile(pa+'/static/abc.html');
// // res.send('屈原');
// });
/* 动态路由,把数据的变量名,写在路由上
/abc/:id/:name id 和 name 此刻都是变量名
可以通过 req.params 来获取路径传递的参数,
req.params 类似 req.query 都是一个对象,获取数据的时候很方便
*/
app.get('/abc/:name/:age',(req,res)=>{
console.log(req.params);
res.send('莲叶何田田'+req.params.name);
});
app.listen(8080,()=>{
console.log('服务启动成功');
});
3.express post请求(内置body-parser 获取前端req内容)
- app.use(bodyParser.urlencoded({ extended:false}));
- app.use(bodyParser.json());
//前端页面
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>post提交</title>
</head>
<body>
姓名: <input type="text" value="" id="username" ><br/>
年龄: <input type="text" value="" id="age" ><br/>
<button id="btn">提交</button>
<p id="msg"></p>
</body>
</html>
<script src="./jquery.js"></script>
<script>
$('#btn').click(function(){
let obj = {
name:$('#username').val(),
age:$('#age').val()
};
$.post('/post',obj,data=>{
console.log(data);
$('#msg').text(data);
});
});
</script>
//后端页面
const express = require('express');
const app = express();
const path = require('path');
// 引入第三方中间件 body-parser
const bodyParser = require('body-parser');
// 使用bodyParser.urlencoded()方法,使node后台支持 application/x-www-form-urlencoded 请求格式
app.use(bodyParser.urlencoded({
extended:false
}));
// 使用bodyParser.json()方法,使node后台支持 application/json 请求格式
app.use(bodyParser.json());
//获取到静态资源所在的路径
let pa = path.join(__dirname,'../static');
app.use(express.static(pa));
app.post('/post',(req,res)=>{
console.log(req.body); // req.body 获取post提交的内容
res.send('李商隐'+req.body.name);
});
app.listen(8080,()=>{
console.log('服务启动成功');
});