通过axios讲解接口参数传递方式
2023-09-02 15:56:23
前端使用 axios 传递参数
1. query 参数
query 参数是通过 URL 传递的,位于 URL 问号 (?) 之后。例如,以下 URL 中包含了一个 query 参数 "name=John":
https://example.com/api/users?name=John
query 参数的格式为 "键=值",多个参数用 "&" 符号连接。例如,以下 URL 包含了两个 query 参数 "name=John" 和 "age=30":
https://example.com/api/users?name=John&age=30
在 axios 中,可以使用 params
选项来传递 query 参数。例如:
axios.get('https://example.com/api/users', {
params: {
name: 'John',
age: 30
}
});
2. body 参数
body 参数是通过 HTTP 请求体传递的。例如,以下 POST 请求的 body 中包含了一个 JSON 对象:
POST /api/users HTTP/1.1
Content-Type: application/json
{
"name": "John",
"age": 30
}
在 axios 中,可以使用 data
选项来传递 body 参数。例如:
axios.post('https://example.com/api/users', {
name: 'John',
age: 30
});
3. path 参数
path 参数是通过 URL 路径传递的。例如,以下 URL 中包含了一个 path 参数 "id=1":
https://example.com/api/users/1
在 axios 中,可以使用 url
选项来传递 path 参数。例如:
axios.get(`https://example.com/api/users/${id}`);
4. FormData 参数
FormData 参数是通过 FormData 对象传递的。FormData 对象是一种特殊的对象,可以存储键值对数据。例如,以下 FormData 对象包含了两个键值对 "name" 和 "age":
const formData = new FormData();
formData.append('name', 'John');
formData.append('age', 30);
在 axios 中,可以使用 formData
选项来传递 FormData 参数。例如:
axios.post('https://example.com/api/users', formData);
后端接收参数
1. query 参数
在后端,可以使用各种框架或语言来接收 query 参数。例如,在 Node.js 中,可以使用 req.query
对象来接收 query 参数。例如:
const name = req.query.name;
const age = req.query.age;
2. body 参数
在后端,可以使用各种框架或语言来接收 body 参数。例如,在 Node.js 中,可以使用 req.body
对象来接收 body 参数。例如:
const name = req.body.name;
const age = req.body.age;
3. path 参数
在后端,可以使用各种框架或语言来接收 path 参数。例如,在 Node.js 中,可以使用 req.params
对象来接收 path 参数。例如:
const id = req.params.id;
4. FormData 参数
在后端,可以使用各种框架或语言来接收 FormData 参数。例如,在 Node.js 中,可以使用 multer
库来接收 FormData 参数。例如:
const multer = require('multer');
const upload = multer();
app.post('/api/users', upload.single('avatar'), (req, res) => {
const name = req.body.name;
const age = req.body.age;
const avatar = req.file;
// ...
});