express路由

express路由模块

  • 安装:在项目所处的目录下,运行如下的终端命令,即可将express安装到项目中使用
    命令:npm i [email protected]

(1)监听GET请求

app.get('请求url',function(req,res) {
    
    /**处理函数/})
//参数1:客户端请求的url地址

(2)监听POST请求

app.post('请求url',function(req,res) {
    
    /**处理函数/})

(3)响应客户端

app.send('处理的内容')

(4)获取url中携带的查询参数

 app.get('/',(req,res)=>{
    
    
// console.log(req.query)
 res.send(req.query)
 })
 app.get('./uesr/:id',(req,res)=>{
    
    
//     console.log(req.params)
    req.send(req.params)
 })

(5)express路由

express路由指的是客户端的请求与服务器之间的映射关系

app.METHOD(PATH,HANDLER)

express由三部分组成,分别是请求的类型,请求的url地址,处理函数

(6)express中间件

中间件的函数必须包含next参数,而路由处理函数中只有req,res

next函数的作用:实现多个中间件连续调用的关键

//定义中间件函数
const express=require('express')
const app=express()
const mw=function(req,res,next) {
    
    
    console.log('d')
next()
}
//定义全局生效的中间件
app.ues(mw)
app.get('/',(req,res) => {
    
    
    res.send('Home fd')
})
app.get('/clock',(req,res) => {
    
    
    res.send('User Page')
})
app.listen(80,() => {
    
    
    console.log('http://127.0.0.1')
})

(7)express写接口

  • 创建API接口

在这里插入图片描述

  • 编写GET接口
apRouter.get('/get'(req,res) => {
    
    
const query=req.query
res.send({
    
    
    //0是请求成功,1表示请求失败
    
status:0,
mag:'GET成功',
    data:query
})
})
  • 编写POST接口

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/m0_61016904/article/details/123605758