众所周知,express在nodejs中的地位非常重要.那么接下来我们来详细看看这个第三方组件吧!
首先需要执行npm install express
来安装
express中文官网
作用
express的作用有点类似于node中的http模块,它可以用来搭建服务器,并且他没有改变nodejs的原有特性,这意味着它可以同时使用nodejs的原生语法.
express的三大核心功能
- 托管静态资源
- 路由
- 中间件
express的使用步骤
- 导入模块
- 创建服务器
- 托管静态资源
- 导入中间件
- 设置路由
- 开启服务器
大致流程如下
// 1.导入资源
const express= require('express');
// 2.创建服务器
let app = express();
// 3.托管静态资源
app.use(express.static('www'));
// 4.配置中间件
const bodyParser = require('bodyParser');
app.use(bodyParser.urlencoded({ extended: false }));
// 5.写路由
app.get('/hero/list',(req,res)=>{
console.log(req.url);
console.log(req.query);
req.send(req.query)
})
app.post('/hero/add',(req,res)=>{
console.log(req.url);
console.log(req.body);
req.send(req.body);
})
// 6.开启服务器
app.listen(3000,()=>{
console.log('sucess!');
})