params和data的差别
export function downFile(url, parameter, method) {
return axios({
url: url,
params: parameter,
method: method ? method : "get",
responseType: "blob",
});
}
// params: parameter,请求的参数,会作为查询字符串附加到 URL 上
export function downFile2(url, parameter, method) {
return axios({
url: url,
method: method,
data: parameter, // 确保请求体包含参数
responseType: "blob", // 指定响应类型为 blob
});
}
//data: parameter,请求体包含的参数。这通常用于发送复杂的数据,例如在 POST 请求中发送 JSON 数据。
data: parameter
和 params: parameter
在 Axios 请求中有不同的用途和行为,它们的主要区别如下:
使用场景示例
GET 请求使用
params
:- 用于发送 URL 查询字符串参数,通常用于
GET
请求。 - 适合发送简单的键值对数据,作为 URL 查询参数的一部分。
-
axios({ url: '/api/example', method: 'get', params: { key1: 'value1', key2: 'value2' } });
-
在上述例子中,数据会作为查询参数附加到 URL 上,例如
/api/example?key1=value1&key2=value2
。 POST 请求使用
data
:- 用于发送请求体中的数据,通常用于
POST
、PUT
、PATCH
等方法。 - 适合发送较大或较复杂的数据,如 JSON 对象、表单数据等
-
axios({ url: 'https://api.example.com/data', method: 'post', data: { name: 'John Doe', age: 30 } }).then(response => { console.log(response.data); });
综上所述,
data: parameter
用于发送请求体数据,适合POST
、PUT
请求;而params: parameter
用于发送 URL 查询字符串参数,适合GET
请求。选择使用哪种取决于你要发送的数据类型和请求方法。
下载doc文件
export function downFile2(url, parameter, method) {
return axios({
url: url,
method: method,
data: parameter, // 确保请求体包含参数
responseType: "blob", // 指定响应类型为 blob
});
}
export function downloadFile2(url, fileName, parameter, method) {
return downFile2(url, parameter, method)
.then((response) => {
const data = response;
const blob = new Blob([data], { type: "application/msword" }); // 设置为 DOC 文件的 MIME 类型
if (typeof window.navigator.msSaveBlob !== "undefined") {
window.navigator.msSaveBlob(blob, fileName);
} else {
const url = window.URL.createObjectURL(blob);
const link = document.createElement("a");
link.style.display = "none";
link.href = url;
link.setAttribute("download", fileName);
document.body.appendChild(link);
link.click();
document.body.removeChild(link); // 下载完成移除元素
window.URL.revokeObjectURL(url); // 释放掉 blob 对象
}
})
.catch((error) => {
console.error("文件下载失败:", error);
});
}
使用
downloadFile2(
"/asset/assetrentcontract/downLoadTemplate",
`${data.contractName + "备案表"}.doc`,
assetRentemplateDTO,
"post"
);