写接口思路是什么?
- 1:创建服务
- 2:定义接口地址
- 3:定义接口请求方式
- 4:如果获取请求参数
- 5:确认接口是做什么? (使用参数做一些内容)
- 6:输出接口运行结果? (怎么给客户端响应)
接口:
1:如何处理请求?
- 1.1 问:传参的方式是什么? 以上就是传参的方式.
1
2
3- query
- params
- body - 1.2问:参数具体内容是什么?
- 服务端开发定义
- 1.3问题:参数的数据格式是什么???
1
2
3
4- xml
- json
- form-data
- urlencode
写接口方式三: router 路由中间件
1 | import Express from "express"; |
- 定义地址:/test/params-value/params-valuve
- 定义的参数:id
- 传参格式 :params 参数, 参数在服务端写好了,前端只需要根据位置 传对应的参数就可以了
- /test/123/sfsf23
- {id:123,token:sfsf23}
1 | router.get('/test/:id/:token',function(req,res){ |
- 如何接受 body 传参 urlencode /json格式数据
- 需要使用第三方中间 body-parser
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23router.post('/b',function(req,res){
console.log('body参数=================>',req.body); // 获取body参数 urlencode / json 数据,formdata 不能获取
// console.log(req);
res.json({
code:'body urlencode 格式数据'
})
})
app.use(function(req,res,next){
console.log("执行中间件,来了老弟.....");
console.log(req.query);
console.log('-------------------分解----------------------------');
next();
})
app.use(bodyParser.urlencoded())
app.use(router)
app.listen(3000, () => {
console.log('服务启动');
})
Author: 李金帅
Link: https://lijinshuai21.github.io/Li_JinShuai_Blog/2022/05/01/node_js%E5%86%99%E6%8E%A5%E5%8F%A3/
Copyright: All articles in this blog are licensed under CC BY-NC-SA 3.0 unless stating additionally.