Express应用
# express
## 简介
web开发应用
## 下载
npm install express
## 中间件
中间件方法和请求处理函数
app.get(‘请求路径‘,‘处理函数‘);
app.post(‘请求路径‘,‘处理函数‘);
## 处理get请求参数
req.query
## 处理post请求参数
使用中间件 body-parser
通过req.body
典型模板
const express = require(‘express‘);
//创建网站服务器
const app = express();
app.get(‘/‘, (req, res) => {
res.send(‘hello world!‘);
});
app.get(‘/news‘, (req, res) => {
//send():会检测响应内容的类型,自动设置状态码
res.send(‘whats up?!‘);
});
app.listen(7788);
console.log(‘app is running!‘);
Cannot set headers after they are sent to the client
res.send() //不支持重复提交!
// 入口全部响应
app.get(‘*‘, (req, res, next) => {
console.log(++count);
next(); //支持跳转
});
app.get(‘/req1‘, (req, res, next) => {
console.log(1111);
res.send(‘hello‘);
console.log(2222);
next();
res.send(‘world‘);
console.log(3333);
next();
});
//中间件:app.use()匹配
app.use((req, res, next) => {
console.log(123);
});
app.get(‘/req1‘, (req, res, next) => {
res.send(req.query.a + ‘—‘ + req.query.b);
});
app.post(‘/post‘, (req, res) => {
console.log(req.body);
res.send(req.body);
});
// 获取文件内容
fs.readFile(‘./2.js‘, ‘utf8‘, (err, data) => {
if (err != null) {
next(err);
} else {
res.send(data);
}
})
//处理错误中间件
app.use((err, req, res, next) => {
res.status(500).send(err.message);
});
express.Router() 获取路由:改变根路径地址
/home作为根目录,进行跳转
http://localhost:8899/home/index
//实现将模块对象统一管理
const express = require(‘express‘);
const app = express();
//创建路由对象
const home = express.Router();
//二级路由 /home/index
home.get(‘/‘, (req, res) => {
res.send(‘home‘);
});
home.get(‘/index‘, (req, res) => {
res.send(‘welcome‘);
});
app.use(‘/home‘, home);
app.listen(8899);
多个根目录:
const app = express();
const home = require(‘./route/home‘);
const admin = require(‘./route/admin‘);
app.use(‘/admin‘, admin);
app.use(‘/home‘, home);
//其他路由
const express = require(‘express‘);
const admin = express.Router();
admin.get(‘/index‘, (req, res, next) => {
res.send(‘/admin/index‘);
next();
});
module.exports = admin;
??访问静态资源问题
//express 访问静态资源
//app.use(express.static(‘public‘));
app.use(‘/static‘, express.static(‘public‘));
模板引擎应用
render && view
//配置模板引擎
app.engine(‘art‘, require(‘express-art-template‘));
//设置模板存放的目录
app.set(‘views‘, path.join(__dirname, ‘views‘));
//设置默认的模板扩展名
app.set(‘view engine‘, ‘art‘);
app.get(‘/index‘, (req, res) => {
res.render(‘index‘);
});
app.get(‘/news‘, (req, res) => {
res.render(‘news‘, {
msg: ‘hello world‘
});
});
//对应views目录下存在如下文件 news.art index.art
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<ul>
<li>{{msg}}</li>
<li>{{msg}}</li>
<li>{{msg}}</li>
</ul>
<p>{{msg}}</p>
</body>
</html>
// 设置目标值
let dataObj = {
msg: ‘hello world‘
};
//或者
app.locals.msg = ‘hello‘;
文件所在当前路径+文件名
//let pathName = path.join(__dirname, ‘./2.js‘);