使用express创建最基本的服务器
//1.导入express
const express=require('express')
//2.创建web服务器
const app=express()
//4.监听客户端的GET和POST请求,并向客户端相应具体内容
app.get('/user',(req,res)=>{
//调用express提供的res.send()方法,向客户端响应一个JSON对象
res.send({name:'zs',age:20,gender:'男'})
})
app.post('/user',(req,res)=>{
//调用express提供的res.send()方法,向客户端响应一个文本字符串
res.send('请求成功!')
})
app.get('/',(req,res)=>{
//通过req.query可以获取到客户端发送过来的查询参数
//注意:默认情况下,req,query是一个空对象
console.log(req.query)
res.send(req.query)
})
app.get('/user/:id',(req,res)=>{
//req.params是动态匹配的url参数,默认是一个空对象
console.log(req.params)
req.send(req.params)
})
//3.启动web服务器
app.listen(80,()=>{
console.log('express server running at http://127.0.0.1')
})
使用express.static对外提供静态资源.
const express=require('express')
const app=express()
//在这里,调用express.static()方法,快速的对外界提供静态资源
app.use(express.static('./clock'))
app.listen(80,()=>{
console.log('express server running at http://127.0.0.1')
})
最简单的路由用法.
const express=require('express')
const app=express()
//挂在路由
app.get('/',(req,res)=>{
res.send('hello world')
})
app.post('/',(req,res)=> {
res.send('Post Request')
})
app.listen(80,()=>{
console.log('http://127.0.0.1')
})
模块化路由.
const express=require('express')
const app=express()
const router=require('./05router')//导入路由模块
app.user(router)//注册路由模块
app.listen(80,()=>{
console.log('http://127.0.0.1')
})
router
const express=require('express')//导入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.use((req,res,next)=>{
console.log('这是最简单的中间件函数')
next()
})
app.get('/',(req,res)=>{
console.log('调用了/这个路由')
res.send('Home page.')
})
app.get('/user',(req,res)=>{
console.log('调用了/user这个路由')
res.send('User page.')
})
app.listen(80,()=>{
console.log('http://127.0.0.1')
})
体验中间件的作用.
const express=require('express')
const app=express()
//这是定义全局中间件的简化形式
app.use((req,res,next)=>{
//获取请求到达服务器的时间
const time=Date.now()
//为req对象挂载自定义属性,从而把时间共享给后面的所有路由
req.startTime=time
next()
})
app.get('/',(req,res)=>{
res.send('Home page.'+req.startTime)
})
app.get('/user',(req,res)=>{
res.send('User page.'+req.startTime)
})
app.listen(80,()=>{
console.log('http://127.0.0.1')
})
定义多个全局中间件.
const express=require('express')
const app=express()
//定义第一个全局中间件
app.use((req,res,next)=>{
console.log('调用了第一个全局中间件')
next()
})
//定义第二个全局中间件
app.use((req,res,next)=>{
console.log('调用了第一个全局中间件')
next()
})
//定义一个路由
app.get('/user',(req,res)=>{
res.send('User page.')
})
app.listen(80,()=>{
console.log('http://127.0.0.1')
})
局部生效的中间件.
//导入express模块
const express=require('express')
//创建express服务器实例
const app=express()
//定义中间件函数
const mw1=(req,res,next)=>{
console.log('调用了局部生效的中间件')
next()
}
//创建路由
app.get('/',mw1,(req,res)=>{
res.send('Home page.')
})
app.get('/user',(req,res)=>{
res.send('User page.')
})
//调用app.listen方法,指定端口号并启动web服务器
app.listen(80,()=>{
console.log('express server running at http://127.0.0.1')
})
同时使用多个局部中间件.
//导入express模块
const express=require('express')
//创建express服务器实例
const app=express()
//定义中间件函数
const mw1=(req,res,next)=>{
console.log('调用了第一个局部生效的中间件')
next()
}
const mw2=(req,res,next)=>{
console.log('调用了第二个局部生效的中间件')
next()
}
//创建路由
app.get('/',mw1,mw2,(req,res)=>{
res.send('Home page.')
})
app.get('/user',(req,res)=>{
res.send('User page.')
})
//调用app.listen方法,指定端口号并启动web服务器
app.listen(80,()=>{
console.log('express server running at http://127.0.0.1')
})
演示错误级别中间件的使用.
//导入express模块
const express=require('express')
//创建express服务器实例
const app=express()
//定义路由
app.get('/',(req,res)=>{
//人为的制造错误
throw new Error('服务器发生了错误')
res.send('Home page.')
})
//定义错误级别的中间件,捕获整个项目的异常错误,从而防止程序崩溃
app.use((err,req,res,next)=>{
console.log('发生了错误'+err.message)
res.send('Error:'+err.message)
})
//调用app.listen方法,指定端口号并启动web服务器
app.listen(80,()=>{
console.log('express server running at http://127.0.0.1')
})
演示内置中间件的使用.
//导入express模块
const express=require('express')
//创建express服务器实例
const app=express()
//通过express.urlencoded()这个中间件来解析表单中的url-encoded格式的数据
app.use(express.urlencoded({extended:false}))
//除了错误界别的中间件,其他中间件必须在路由之前
//通过express.json()这个中间件,解析表单的JSON格式的数据
app.use(express.json())
app.post('/user',(req,res)=>{
//在服务器,可以使用req.body这个属性来接收客户端请求体数据
//默认情况下,如果不配置解析表单数据的中间件,则req.body默认等于undefined
console.log(req.body)
res.send('ok')
})
app.post('/book',(req,res)=>{
//在服务器端,可以通过req,body来获取JSON格式的表单数据和url-encoded格式的数据
console.log(req.body)
res.send('ok')
})
//调用app.listen方法,指定端口号并启动web服务器
app.listen(80,()=>{
console.log('express server running at http://127.0.0.1')
})
演示body-parse中间件的使用.
//导入express模块
const express=require('express')
//创建express服务器实例
const app=express()
//导入解析表单数据的中间件
const parser=require('body-parser')
//使用app.use()注册中间件
app.use(parser.urlencoded({extend:false}))
app.post('/user',(req,res)=>{
//如果没有配置任何解析表单数据的中间件,则req.body默认等于undefined
console.log(req.body)
res.send('ok')
})
//调用app.listen方法,指定端口号并启动web服务器
app.listen(80,()=>{
console.log('express server running at http://127.0.0.1')
})
自定义解析表单数据的中间件.
//导入express模块
const express=require('express')
//创建express服务器实例
const app=express()
//导入Node.js内置的querystring模块
const qs=require('querystring')
//这是解析表单数据的中间件
app.use((req,res,next)=>{
//定义中间件具体的业务逻辑
//1.定义一个str字符串,专门用来存储客户端发送过来的请求体数据
let str=''
//2.监听req的data事件
req.on('data',(chunk)=>{
//拼接请求体数据,隐式转换为字符串
str+=chunk
})
//3.监听req的end事件
req.on('end',()=>{
//在str中存放的是完整的请求体数据
//console.log(str)
//TODO:把字符串格式的请求体数据,解析成对象格式
const body=qs.parse(str)
req.body=body
next()
})
})
app.post('/user',(req,res)=>{
res.send(req.body)
})
//调用app.listen方法,指定端口号并启动web服务器
app.listen(80,()=>{
console.log('express server running at http://127.0.0.1')
})
对自定义的中间件进行模块化的拆分.
//导入express模块
const express=require('express')
//创建express服务器实例
const app=express()
//1.导入自己封装的中间件模块
const customBodyParser=require('./16custom-body-parser')
//2.将自定义的中间件函数,注册为全局可用的中间件
app.use(customBodyParser)
app.post('/user',(req,res)=>{
res.send(req.body)
})
//调用app.listen方法,指定端口号并启动web服务器
app.listen(80,()=>{
console.log('express server running at http://127.0.0.1')
})
custom-body-parser.
//导入Node.js内置的querystring模块
const qs=require('querystring')
const bodyParser=((req,res,next)=>{
//定义中间件具体的业务逻辑
//1.定义一个str字符串,专门用来存储客户端发送过来的请求体数据
let str=''
//2.监听req的data事件
req.on('data',(chunk)=>{
//拼接请求体数据,隐式转换为字符串
str+=chunk
})
//3.监听req的end事件
req.on('end',()=>{
//在str中存放的是完整的请求体数据
//console.log(str)
//TODO:把字符串格式的请求体数据,解析成对象格式
const body=qs.parse(str)
req.body=body
next()
})
})
module.exports=bodyParser
使用express写接口.
//导入express模块
const express=require('express')
//创建express服务器实例
const app=express()
//配置解析表单数据的中间件
app.use(express.urlencoded({extended:false}))
//必须在配置cors中间件之前,配置JSONP的接口
app.get('/api/jsonp',(req,res)=>{
//TODO:定义JSONP接口具体的实现过程
//1.得到函数名称
const funcName=req.query.callback
//2.定义要发送到客户端的数据对象
const data={name:'zs',age:22}
//3.拼接出一个函数的调用
const scriptStr=`${funcName}(${JSON.stringify(data)})`
//4.把拼接好的字符串,响应给客户端
res.send(scriptStr)
})
//一定要在路由之前,配置cors这个中间件,从而解决接口跨域问题
const cors=require('cors')
app.use(cors())
//导入路由模块
const router=require('./18apiRouter')
//把路由模块注册到app上
app.use('/api',router)
//启动服务器
app.listen(80,()=>{
console.log('express server running at http://127.0.0.1')
})
apiRouter.
const express=require('express')
const router=express.Router
//在这里挂载对应的路由
router.get('/get',(req,res)=>{
//通过req.query获取客户端通过查询字符串,发送到服务器的数据
const query=req.query
//调用res.send()方法,向客户端响应处理结果
res.send({
status:0,//0表示处理成功,1表示处理失败
msg:'GET请求成功',//状态的描述
data:query//需要响应给客户端的数据
})
})
//定义post接口
router.post('/post',(req,res)=>{
//通过req.body获取请求体中包含的url-encoded格式的数据
const body=req.body
//调用res.send()方法,向客户端响应结果
res.send({
status:0,
msg:'POST请求成功',
data:body
})
})
module.exports=router
Q.E.D.