# Express 基本使用
| |
| const express = require('express') |
| |
| |
| const app = express() |
| |
| |
| app.listen(80, () => { |
| console.log('express server running at http://127.0.0.1'); |
| }) |
# 监听 GET/POST 请求
- 通过
app.get()||app.post()
, 可以监听客户端的 GET 请求,具体格式如下
| |
| |
| |
| |
| app.get('URL', (req, res) => { |
| console.log('express server running at http://127.0.0.1'); |
| }) |
| |
| app.post('URL', (req, res) => { |
| console.log('express server running at http://127.0.0.1'); |
| }) |
- 通过
res.send()
方法,可以把处理好的内容,发送给客户端
| app.get('/user', (req, res) => { |
| |
| res.send({ name: 'saber', age: 16 }) |
| }) |
| |
| app.post('/user', (req, res) => { |
| |
| res.send('The request is successful') |
| }) |
# send 响应数据
- 通过
res.send()
方法,可以把处理好的内容,发送给客户端
| |
| const express = require('express') |
| |
| |
| const app = express() |
| |
| |
| app.listen(8001, (req, res) => { |
| console.log(req, res); |
| console.log('express server running at http://127.0.0.1'); |
| }) |
| |
| |
| app.get('/user', (req, res) => { |
| |
| res.send({ name: 'saber', age: 16 }) |
| }) |
| |
| app.post('/user', (req, res) => { |
| |
| res.send('The request is successful') |
| }) |
# req.query
- 通过
req.query
对象,可以访问到客户端通过查询字符串的形式,发送到服务器的参数
| |
| |
| app.get('/user', (req, res) => { |
| |
| |
| console.log(req.query); |
| |
| |
| |
| |
| res.send(req.query) |
| }) |
# req.params
- 通过
req.params
对象,可以访问到 URL 中,通过 :
匹配到的动态参数
| |
| |
| |
| app.get('/user/:id', (req, res) => { |
| console.log(req.params); |
| |
| res.send(req.params) |
| }) |
# express.static()
- express 提供了一个函数
express.static()
。通过它,可以非常方便创建一个静态资源服务器
- 如果需要托管多个静态资源目录,请多次调用
express.static()
函数,访问静态资源是,会根据目录的添加顺序查找所需文件
| const express = require('express') |
| |
| const app = express() |
| |
| |
| app.use(express.static('path1')) |
| app.use(express.static('path2')) |
| |
| app.listen(8001, (req, res) => { |
| console.log('express server running at http://127.0.0.1'); |
| }) |
- 希望托管的静态资源访问路径之前,挂载路径前缀,如下
| app.use('/public', express.static('path)) |
# express 路由
- 在 Express 中路由指的是客户端的请求与服务器处理函数之间的映射关系
- Express 中的路由分 3 部分组成,分别是请求的类型 、请求的 URL 地址、 处理函数 ,格式如下
| APP[METHOD](PATH, HANDLER) |
| |
| app.get('/', (req, res) => { |
| res.send('get request') |
| }) |
| |
| app.post('/', (req, res) => { |
| res.send('post request ') |
| }) |
# 路由 DEMO
| const express = require('express') |
| |
| const router = express.Router() |
| |
| router.get('/username', (req, res) => res.send(`<pre>username request</pre>`)) |
| |
| router.post('/password', (req, res) => res.send(`<pre>password request</pre>`)) |
| |
| module.exports = router |
| |
| |
| const express = require('express') |
| const app = express() |
| |
| |
| const router = require('./router') |
| |
| |
| app.use('/api', router) |
| |
| |
| |
| app.listen(8001, () => console.log('The server is started successfully')) |