1.创建接口
// 导入 express 模块
const express = require('express')
// 创建 express 的服务器实例
const app = express()
// 导入中间件第三方包
const cors = require('cors')
// 配置中间件
app.use(cors())
// 配置解析表单数据的中间件
//注意:如果要获取 URL-encoded 格式的请求体数据,必须配置中间件 app.use(express.urlencoded({ extended: false }))
app.use(express.urlencoded({ extended: false }))
app.get('/api', (req, res) => {
res.send()
})
// 导入路由模块
const router = require('./创建routerAPI路由模块')
// 把路由模块,注册到 app 上
app.use('/api', router)
// 调用 app.listen 方法,指定端口号并启动 web 服务器
app.listen(80, () => {
console.log('express server running at http://127.0.0.1');
})
2.创建router.js路由模块
// router.js
// 导入 express 模块
const express = require('express')
const router = express.Router()
// 在这里挂载对应的路由
// 通过 req.query 获取客户端通过查询字符串发送到服务器的数据
router.get('/get',(req, res)=> {
const query = req.query
// 调用 res.send() 方法,想客户端响应处理的结果
res.send({
status: 0, // 0 表示处理成功,1 表示处理失败
msg:'GET 请求成功', // 状态描述
data:query // 需要响应给客户端的数据
})
})
// 定义 POST 接口
// 通过 req.body 获取请求题中包含的 url-encoded 格式的数据
router.post('/post', (req, res) => {
const body = req.body
res.send({
status: 0,
msg:'post 请求成功',
data: body
})
})
//3.暴露
module.exports = router