配置文件
npm init -y
安装
cnpm install express --save
快速创建
全局安装
cnpm install -g express-generator
在项目目录中创建项目
express --view=ejs myapp
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-VWdhSgMX-1604383470734)(C:\Users\凉城\AppData\Roaming\Typora\typora-user-images\image-20201103113813512.png)]
const express = require(‘express’)//导入express包,是一个函数
const app = express()//app接收,express函数的返回对象
const port = 3000//端口常量
基础四种方法
配置一个get请求的路由app.get()
app.get('/get', (req, res) => { res.send('Hello World!') })
app.post('/post', (req, res) => { res.send('Got a POST request') })
app.put('/put', (req, res) => {res.send('Got a PUT request at /user')})
app.delete('/delete', (req, res) => {res.send('Got a DELETE request at /user') })
all方法与绑定的路由方式无关
app.all('/', (req, res) => {res.send('所有数据')})
直接使用use分发可以处理所有的路由请求
app.use((req, res) => {res.send('ok')})
app.listen(port, () => console.log(当前项目运行在端口 ${port}!
))
利用Express托管静态文件
通过如下代码就可以将public
目录下的图片、css文件、JavaScript文件对外开放访问了:
app.use(express.static('public'))
现在,你就可以访问public
目录中的所有文件了:
http://localhost:3000/images/kitten.jpg
http://localhost:3000/css/style.css
http://localhost:3000/js/app.js
http://localhost:3000/images/bg.png
http://localhost:3000/hello.html
为由express.static
职能,指定挂载路径对于静态目录,如下所示:
app.use('/static', express.static('public'))
现在,你就可以通过带有/static
前缀地址来访问public
目录中的文件了.
http://localhost:3000/static/images/kitten.jpg
http://localhost:3000/static/css/style.css
http://localhost:3000/static/js/app.js
http://localhost:3000/static/images/bg.png
http://localhost:3000/static/hello.html
中间件(next 衔接下一步)
function aaa(req, res, next) {
console.log(1);
next()
}
function bbb(req, res, next) {
console.log(2);
next()
}
function ccc(req, res, next) {
console.log(3);
next()
}
app.use([aaa, bbb, ccc])
每次刷新集成终端都会显示