// 1.导入express、路由模块
const express = require('express')
// 2.创建web服务器
const server = express()
// 3.监听服务器的启动
server.listen(80,()=>{
console.log("web服务器启动了 http://127.0.0.1:80");
})
// 4.1post请求通过body传参并为raw类型中json格式传参时,通过express.json()这个中间件,解析表单中的JSON格式的数据,不解析就拿不到req.body
server.use(express.json()) // 解析JSON格式数据
// 4.2post请求通过body传参并为x-www-form-urlcoded类型传参时,通过express.urlencoded()这个中间件,解析表单中的 url-encoded 格式的数据,不解析就拿不到req.body
server.use(express.urlencoded({extended:false})) // 解析url-encoded 格式的数据
// 5.挂载具体的路由-接口
router.get('/kanno',(req,res)=>{
res.send({
name:"堀北 铃音",
classroom:"D class"
})
})
router.get('/user',(req,res)=>{
res.send({
name:"绫小路 清隆",
classroom:"D class"
})
})
router.post('/kanno',(req,res)=>{
res.send({
name:"一之濑 帆波",
classroom:"B class"
})
})
// 6.请求接口实例
// 使用postman工具请求以下接口
// get请求:http://127.0.0.1:80/user
// post请求:http://127.0.0.1:80/kanno
// req.query:获取的是路由路径上传的数据
// req.body:获取的是通过请求体传递的数据
node中使用express写接口
最新推荐文章于 2024-09-08 21:36:12 发布