Express笔记

概念

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);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值