axios 发送请求的传参方式,post表单提交
axios
axios请求方法有get、post、put、patch、delete
get
作用:获取数据
默认’Content-Type’: ‘application/json’
axios.get('/url/adrress') // 发请求
.then((res)=>{ // 处理响应数据
console.log(res.data)
}).catch((err) => {
consloe.log(err) //处理错误
})
2.要传参 params
会将传参拼接到请求地址url中:http://localhost:8080/url/address?id=12
(a)对象写法:
传参格式: {params: param}
axios.get('/url/adrress',{
params: {
id: 12
}
}).then((res)=>{
console.log(res)
})
或写为:
axios({
method: 'get',
url: '/url/adrress',
params: { id: 12 },
}).then((res)=>{
console.log(res)
})
(b)字符串拼接写法:
axios({
method: 'GET',
url: '/url/adrress?id=' + '12',
}).then((res)=>{
console.log(res)
})
post
作用: 提交数据(表单提交+ 文件上传)
post接受三个参数,url,data,config
[1] 传参格式为raw,即JSON格式 (application/json)
如果你想以JSON格式发送数据,你可以设置请求头为’application/json’,并将数据作为JSON字符串发送。
const data = { key1: 'value1', key2: 'value2' };
axios.post('src/address', data, {
headers: {
'Content-Type': 'application/json'
}
}).then((res)=>{
console.log(res)
})
默认情况下,axios 将 JavaScript 对象序列化为 JSON。
const data = { key1: 'value1', key2: 'value2' };
axios.post('src/address', data).then((res) => {
console.log(res)
})
其他写法:
const data = { key1: 'value1', key2: 'value2' };
axios({
method:'post',
url:'src/address',
data: data
}).then(...)
[2] 传参格式为多部分/表单数据 (multipart/form-data)
以前写表单传参:
var formData=new FormData();
formData.append('user',123456);
formData.append('pass',12345678);
formData.append('file', file);
axios.post("/src/address",formData)
.then(...)
从 v0.27.0 开始,如果请求 Content-Type 标头设置为 multipart/form-data,axios 支持自动将对象序列化为 FormData 对象。
import axios from 'axios';
let data = {
user: {
name: 'Dmitriy'
},
pass: 1231
file: fs.createReadStream('/foo/bar.jpg')
}
axios.post('https://httpbin.org/post', data , {
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(...);
[3] URL 编码形式 (application/x-www-form-urlencoded)
该格式不常用
如果 content-type 标头设置为 application/x-www-form-urlencoded,axios 会自动将数据对象序列化为 urlencoded 格式。
这在浏览器和 node.js 中都有效:
const data = {
x: 1,
arr: [1, 2, 3],
arr2: [1, [2], 3],
users: [{name: 'Peter', surname: 'Griffin'}, {name: 'Thomas', surname: 'Anderson'}],
};
await axios.post('https://postman-echo.com/post', data,
{headers: {'content-type': 'application/x-www-form-urlencoded'}}
);
put
作用:更新数据(将所有数据传回到服务端)
用法与post大体相同
patch
作用:更新数据(只将修改的数据传回到后端)
用法与post大体相同
delete
删除数据
1. url删除法
参数格式:{params: param}
//直接从url里面删除
axios.delete('/src/address',{
params:{
id:12
}
}).then(...)
2.请求体删除法
参数格式:{data: param}
axios.delete('/src/address',{
data:{
id:12
}
}).then(...)