2022/8/17 都是关于接口的内容 express挂载,中间件,CORS跨域问题请求

这篇博客探讨了如何使用Express创建GET和POST接口,包括路由挂载、中间件的使用,以及处理CORS跨域问题。内容涵盖全局和局部中间件、错误处理中间件,还介绍了JSONP接口的实现。
摘要由CSDN通过智能技术生成

express路由挂载实例,不常用

const express = require('express')
const app = express()
app.get('/',function(req,res){
    res.send('hello')
})
app.post('/',(req,res)=>{
    res.send('hello world')
})

app.listen(8080,()=>{
    console.log('http://127.0.0.1:8080')
})

模块化路由才是常用

const express = require('express')
const app = express()
//导入路由模块
const router = require('./router')

//注册路由模块,app.use注册全局中间件
//注册路由模块,加访问前缀
//app.use('/api',router)
app.use(router)
app.listen(8080,()=>{
    console.log('at http://127.0.0.1:8080')
})


----------------------------------
//导入express
const express = require('express')
//创建路由对象
const router = express.Router()


//挂在具体路由
router.get('/user/list',(req,res)=>{
 res.send('Get user list')
})
router.post('/user/add',(req,res)=>{
    res.send('Add New User')
})
//向外导入
module.exports = router

简单中间件函数的写法,有全局生效中间件

const express = require('express')
const app = express()
//定义简单的中间件
const mw = function(req,res,next){
    console.log('这是最简单的中间件')
    //把流转关系给下一个路由或中间件
    next()
}
//mw注册为全局生效中间件
app.use(mw) 
app.get('/',(req,res)=>{
    res.send('hello')
})
app.get('/user',(req,res)=>{
    res.send('user page')
    console.log('111')
})
app.listen(8080,()=>{
    console.log('http://127.0.0.1:8080')
})

全局中间件的简化形式

app.use((req,res,next)=>{
    console.log('简化')
    next()
})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值