Express
介绍
{: height=71% width=71%}
{: height=71% width=71%}
Express
的基本使用
终端运行命令安装 npm i express@4.17.1
创建基本的Web服务器
// 1. 导入 express
const express = require('express')
// 2. 创建 web 服务器
const app = express() //得到一个服务器实例
// 3. 启动 web 服务器
app.listen(80, () => {
console.log('express server running at http://127.0.0.1')
})
// 1. 导入 express
const express = require('express')
// 2. 创建 web 服务器
const app = express()
// 4. 监听客户端的 GET 和 POST 请求,并向客户端响应具体的内容
app.get('/user', (req, res) => {
// 调用 express 提供的 res.send() 方法,向客户端响应一个 JSON 对象
res.send({ name: 'zs', age: 20, gender: '男' })
})
app.post('/user', (req, res) => {
// 调用 express 提供的 res.send() 方法,向客户端响应一个 文本字符串
res.send('请求成功')
})
app.get('/', (req, res) => {
// 通过 req.query 可以获取到客户端发送过来的 查询参数
// 注意:默认情况下,req.query 是一个空对象
console.log(req.query)
res.send(req.query)
})
// 注意:这里的 :id和:username 是动态的参数。名字可以改。
app.get('/user/:ids/:username', (req, res) => {
// req.params 是动态匹配到的 URL 参数,默认也是一个空对象
console.log(req.params)
res.send(req.params)
})
// 3. 启动 web 服务器
app.listen(80, () => {
console.log('express server running at http://127.0.0.1')
})
托管静态资源
const express = require('express')
const app = express()
// 在这里,调用 express.static() 方法,快速的对外提供静态资源
//即你访问服务器地址/index.html时访问到的是clock下的index.html
//访问服务器地址/files/index.html时访问到的是files下的index.html
app.use('/files', express.static('./files'))
app.use(express.static('./clock'))
app.listen(80, () => {
console.log('express server running at http://127.0.0.1')
})
nodemon
安装nodemon
,npm i -g nodemon
Express
路由
路由的介绍
{: height=46% width=46%}
路由的使用
1.最简单的用法,直接挂载到app上(很少用)
2.模块化路由
为了方便对路由进行模块化的管理
,Express不建议将路由直接挂载到app上,而是推荐将路由抽离为单独的模块
- 创建路由模块
- 注册路由模块
Express
中间件介绍
Express
中间件初体验
定义一个最简单的中间件函数
- 比如客户端发起get请求后,
先到中间件输出“这是一个最简单的中间件函数”
,然后没有后续中间件了,最后到路由输出”调用了 / 这个路由“
{ :height=68% width=68%}
中间件的分类
{ :height=78% width=78%}
自定义中间件
{: width=71%}
对自定义的中间件进行模块化的拆分
中间件函数 拎出来作为一个模块
{: width=78%}
再把中间件函数那个模块导进来
{: width=78%}
基于express
写接口
{: width=68%}
{: width=55%}
{: width=68%}
{: width=71%}
{: width=71%}
跨域问题
回顾JSONP
接口