Express

配置文件

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])

每次刷新集成终端都会显示

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值