1.URL参数
URL参数直接附加在URL后面,通常用于GET请求。
axios.get('/user?id=12345&name=John')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
2.查询参数
查询参数通常用在GET请求中,可以通过params属性传递。
axios.get('/user', {
params: {
id: 12345,
name: 'John'
}
})
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
3.POST请求体数据
在POST请求中,通常将数据放在请求体中。可以通过data属性传递JSON对象。
axios.post('/user', {
id: 12345,
name: 'John'
})
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
4.FormData数据(文件上传等)
对于需要上传文件或其他非JSON数据的场景,可以使用FormData。
const formData = new FormData();
formData.append('file', fileInput.files[0]); // fileInput是<input type="file">元素
formData.append('id', '12345');
formData.append('name', 'John');
axios.post('/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data' // 不设置时,Axios会自动设置,但仍需明确指出以避免潜在问题
}
})
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
5.URL编码的表单数据(application/x-www-form-urlencoded)
对于需要使用application/x-www-form-urlencoded格式的POST请求,可以使用URLSearchParams。
const params = new URLSearchParams();
params.append('id', '12345');
params.append('name', 'John');
axios.post('/user', params.toString(), {
headers: {
'Content-Type': 'application/x-www-form-urlencoded' // 需要明确设置Content-Type头信息
}
})
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
或者使用qs库将对象转换为查询字符串:
import qs from 'qs'; // 首先需要安装qs库:npm install qs
const data = qs.stringify({ id: '12345', name: 'John' }); // 使用qs库转换对象为查询字符串格式的字符串
axios.post('/user', data, {
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
})...; // 同上处理响应等。