概念
web开发框架
下载
npm install express
使用
导入 express
包
const express = require('express');
创建网站服务器
// 创建网站服务器
const app = express();
监听 get
请求
app.get('/', (req, res) => {
// express 自动封装了 send() 方法
res.send('hello World!');
});
监听访问端口
app.listen(8080);
// 给个提示语
console.log('web 服务器已经启动,请访问http://localhost:8080');
放行处理请求
app.get('/req1', (req, res, next) => {
console.log(1111);
// 放行本次请求处理,给后面请求处理
next();
});
app.get('/req1', (req, res) => {
console.log(2222);
});
中间件
一定要放行
中间件方法和处理函数
函数从上到下依次执行,中间件要在最后请求之前
app.get('请求路径', '处理函数');
app.post('请求路径', '处理函数');
get/post请求获取参数
get请求:req.query
// 访问 localhost://8080/?a=10&b=30
app.get('/', (req, res) => {
// res.send(req.query);
res.send(req.query.a + '-' + req.query.b);
});
// 页面打印出 {a: 10, b" 30}
post请求:需要下载body-parser
// 利用 postman 测试
app.post('/', (req, res) => {
res.send(req.body);
});
// 页面打印出
// 安装
npm i body-parser
// 导入
const bodyParser = require('body-parser');
// 使用 注意:一定要写在 post 监听方法之前
app.use(bodyParser.urlencoded({ extended: true }));
app.use
可以用来做提示公告
app.use((req, res, next) => {
res.send('公司网站正在维护,请于次日8:00后访问,敬请谅解');
next();
});
用来登录验证
let isLogin = false;
if (isLogin) {
next();
} else {
res.send('您还未登录,请登录后再进行操作');
}
})
路由对象
const express = require('express');
const app = express();
const home = express.Router();
home.get('/index', (req, res) => {
res.send('welcome');
});
app.use('/home', home);
app.listen(7878);
访问静态资源
const express = require('express');
const app = express();
// 访问 localhost:7878/index.html
app.use(express.static('static'));
// 访问 localhost:7878/static/index.html
app.use('/static', express.static('static'));
app.listen(7878);
express整合模板引擎
下载
npm install art-template express-art-template
使用
const express = require('express');
const path = require('path');
const app = express();
// 配置模板引擎
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', {
msg: 'hello'
});
});
// 使用以下代码 可以不用在res.render()中添加{}内容
app.locals.msg = 'hello';
app.listen(8080);