post接口和get请求
一、 get接口
req.query属性
app.get('/get', function(req, res) {
// 直接返回对象
console.log(req.query)
})
二、post接口
1.普通键值对
// 普通键值对
app.use(express.urlencoded())
// 普通键值对提交
app.post('/post', (req, res) => {
console.log(req.body)
res.json(req.body)
})
2.复杂json
// json
app.use(express.json())
// json提交
app.post('/postJSON', (req, res) => {
console.log(req.body)
res.json(req.body)
})
3.form-data文件上传
// 引入multer包
const multer = require('multer')
// 配置
const upload = multer({ dest: 'uploads/' })
// form-data文件上传
app.post('/admin/article_publish', upload.single('cover'), (req, res) => {
console.log(req.body)
res.json(req.body)
})
三、总结
1.详看图示:
content-type常见有三种取值
content-type的值 | 表示请求体的数据格式 | 示例 |
---|---|---|
application/x-www-form-urlencode | 普通键值对象 | a=2&c=1 |
application/json | json对象 | {a:1,b:{c:1}} |
multipart/form-data | 上传文件 | file |
传参方式 | 前端 content-type | 后端框架express |
---|---|---|
请求行 | get方式 | req.query |
请求体 | application/x-www-form-urlencode | app.use(express.urlencoded()); req.body |
请求体 | application/json | app.use(express.json()); req.body |
请求体 | multipart/form-data | 1. 引入包 const multer = require(‘multer’); 2. 配置app.post(’/apiname’, upload.single(), req.body) |
2.post接口与get请求不同
表示的操作不同:get一般用来做查询,post一般用来添加;
传参不同:get的参数只能在请求行中通过查询字符串来传递, post一般是通过请求体(它也可以通过请求行来传递)来传递的。