创建web服务器
const express=require('express')
//创建服务器
const app=express()
app.listen(80,()=>{
console.log('express服务器启动成功 127.0.0.1')
})
创建API路由模块(统一接口)
//导入express
const express=require('express')
//创建路由对象
const Router=express.Router()
//向外导出路由
module.exports=Router//之前={对象 对象里面是属性 可以做一个省略}
const express=require('express')
//创建服务器
const app=express()
//导入路由模块
const router=require('./api路由模块')
//把路由模块注册到app上 ——app.use作用注册全局中间件
app.use('/api',router)//请求到达服务器 需要进行中间件的处理--挨个进行路由的匹配_统一前缀
app.listen(80,()=>{
console.log('express服务器启动成功 127.0.0.1')
})
编写GET接口(//get请求使用req.query post请求使用req.body)
//通过req.query获取客户端通过查询字符串获取发送到服务器的数据
//导入express
const express=require('express')
//创建路由对象
const Router=express.Router()
Router.get('/get',(req,res)=>{
//通过req.query获取客户端通过查询字符串获取发送到服务器的数据
const query=req.query //get请求使用req.query post请求使用req.body
res.send(//服务器的响应
{
status:0,//0表示处理成功 1表示处理失败
msg:'GET 请求成功!',//状态的描述
data:query //响应给客户端的数据
}
)
})
//向外导出路由
module.exports=Router//之前={对象 对象里面是属性 可以做一个省略}
编写GET接口( post请求使用req.body)
//通过req.body获取(请求体中包含url-encoded格式的数据 ,需要在路由模块之前配置解析表单数据的中间件)客户端通过查询字符串获取发送到服务器的数据
//导入express
const express=require('express')
//创建路由对象
const Router=express.Router()
//定义get接口
Router.get('/get',(req,res)=>{
//通过req.query获取客户端通过查询字符串获取发送到服务器的数据
const query=req.query //get请求使用req.query post请求使用req.body
res.send(//服务器的响应
{
status:0,//0表示处理成功 1表示处理失败
msg:'GET 请求成功!',//状态的描述
data:query //响应给客户端的数据
}
)
})
//定义post接口
Router.post('/post',(req,res)=>{
//通过req.query获取客户端通过查询字符串获取发送到服务器的数据
const body=req.body //get请求使用req.query post请求使用req.body
res.send(//服务器的响应
{
status:0,//0表示处理成功 1表示处理失败
msg:'POST 请求成功!',//状态的描述
data:body //响应给客户端的数据
}
)
})
//向外导出路由
module.exports=Router//之前={对象 对象里面是属性 可以做一个省略}
const express=require('express')
//创建服务器
const app=express()
//配置解析表单数据的中间件
app.use(express.urlencoded({extended:false}))
//导入路由模块
const router=require('./api路由模块')
//把路由模块注册到app上 ——app.use作用注册全局中间件
app.use('/api',router)//请求到达服务器 需要进行中间件的处理--挨个进行路由的匹配_统一前缀
app.listen(80,()=>{
console.log('express服务器启动成功 127.0.0.1')
})