express简单理解及搭建服务器历程

express是专门开发web服务器的插件

web服务器分为:

  1. web网站服务器
  2. api接口服务器

注意点:
这个给客户端发送数据是send(),不同于原生的http模块,原生的是end()是不能直接发送对象的,需要注意

首先是安装到项目,并引用

npm i express
const express = require('express')
const app = express()

简单使用

app.get('/user/:id', (request, response) => {
    // end()不能直接传对象,转成字符串
    //response.end('{ "name": "张三", "age": 20, "gender": "男" }')
    //使用send()
	response.send({ name: "张三", age: 20, gender: "男" })
    //前端请求参数在request.query中
    console.log(request.query)//{}这个参数形式是 http://url?key=value&key=value
   // 动态参数请求地址参数在params中  /user/aaa?name=zhangsan
    console.log(request.params) //{id:aaa}
})
app.post('/user', (request, response) => {
        response.send('请求成功')
    })



// express静态资源服务器,express在指定静态服务器中查找文件,但是目录名不会出现在url中
// 托管多个时候在没有加前缀或者前缀一样首,是按先后顺序加载静态资源的
//我查找的是test.json这个文件,实际是返回的是当前文件夹file中的test.json
 app.use(express.static('./file'))//http://127.0.0.1:8081/test.json
 app.use(express.static('./resources'))//http://127.0.0.1:8081/test.json
// 加入前缀区分
app.use('/ab', express.static('./file'))//http://127.0.0.1:8081/ab/test.json
app.use('/abc', express.static('./resources'))//http://127.0.0.1:8081/abc/test.json

app.listen(8081, () => {
    console.log('启动成功')
})

express路由

路由是一种映射关系
在express中是前端请求与服务端接口的url

app.get('/', (request, response) => {
    response.send('get请求/')
})
app.post('/', (request, response) => {
    response.send('post请求/')
})
app.get('/ts', (request, response) => {
    response.send('get请求/ts')
})
app.post('/ts', (request, response) => {
    response.send('post请求/ts')
})
app.get('/ts/a', (request, response) => {
    response.send('get请求/ts/a')
})
app.post('/ts/a', (request, response) => {
    response.send('post请求/ts/a')
})
  • 路由是自上而下匹配的越靠前服务权重越大
  • 前端请求请求类型和url要保持一致

模块化路由

由于这么挂载当路由特别多时候文件特别大,不好维护,需要单独把路由模块化
步骤:

  1. 新建路由模块js
  2. 创建路由对象express.Router()
  3. 向对象上挂在路由
  4. 向外通过module.exports向外共享路由对象
  5. 使用app.use()使用模块
//路由模块
const express = require('express')
const router = express.Router()
router.get('/ts', (request, response) => {
    response.end('get请求/ts')
})
router.post('/ts', (request, response) => {
    response.end('post请求/ts')
})

module.exports = router

module.exports = router注意这个地方是把router整个暴露给exports,不能是module.exports = {router:router}

使用路由模块

使用app.use()

const express = require('express')
const router = require('./router')
const app = express()
app.use(router)
app.listen(8081, () => {
    console.log('启动成功')
})

同时可以统一为路由添加前缀,类似与静态资源在调用app.use()的时候添加第一个参数

app.use('/api',router)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值