# 业务
# 跨域方法
- CORS跨域
- JSONP跨域
- 代理跨域
# CORS跨域
CORS跨域 - 服务端设置, 前端直接调用
说明: 后台允许前端某个站点进行访问
CORS是一个W3C标准,全称是"跨域资源共享"(Cross-origin resource sharing),它允许浏览器向跨源服务器,发出XMLHttpRequest请求,从而克服了AJAX只能同源使用的限制。
如果服务器允许跨域,需要在返回的响应头中携带下面信息:
Access-Control-Allow-Origin: http://manage.leyou.com
Access-Control-Allow-Credentials: true
Content-Type: text/html; charset=utf-8
- Access-Control-Allow-Origin:可接受的域,是一个具体域名或者*,代表任意
- Access-Control-Allow-Credentials:是否允许携带cookie,默认情况下,cors不会携带cookie,除非这个值是true
# JSONP跨域
# 接口代理
通过修改nginx服务器配置来实现
在vue中使用
- 创建vue.config.js
module.exports = {
devServer: {
host: 'locahost',
port: 8080,
proxy: {
'/api': {
target: 'https://www.baidu.com',
changeOrigin: false,
}
}
}
}
# Vue,React 中利用的 axios 进行下载 word,excel
# 使用 axios 下载 excel 表格
this.axios.({
methods: 'POST',
header: {'Content-Type': 'application/xls'}, // http请求类型
responseType: 'blob', // 返回格式,默认JSON,可选arraybuffer、blob、document、json、text、stream
url: url,
data: data
}).then(res => {
//application/vnd.openxmlformats-officedocument.spreadsheetml.sheet 这里表示xlsx类型
let blob = new Blob([res.data],{
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
});
let downloadElement = document.createElement('a');
let href = window.URL.createObjectURL(blob);
downloadElement.href = href;
downloadElement.download = '反馈消息表.xls';
document.body.appendChild(downloadElement);
downloadElement.click();
document.body.removeChild(downloadElement);
window.URL.revokeObjectURL(href);
}).catch(err => {
console.log(err);
})
# 封装
/**
data
filname 文件类型名称
excel: .xls
word: .docx
txt: .txt
mime:
excel: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8
word: application/msword
txt: application/octet-binary
*/
const fileDownload = (data, filename, mime) => {
// mime type值 application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
let blob = new Blob([data], { type: mime || "application/octet-stream" });
if (typeof window.navigator.msSaveBlob !== "undefined") {
window.navigator.msSaveBlob(blob, filename);
} else {
let blobURL = window.URL.createObjectURL(blob);
let tempLink = document.createElement("a");
tempLink.href = blobURL;
tempLink.setAttribute("download", filename);
if (typeof tempLink.download === "undefined") {
tempLink.setAttribute("target", "_black");
}
document.body.appendChild(tempLink);
tempLink.click();
document.body.removeChild(tempLink);
window.URL.revokeObjectURL(blobURL);
}
};
# 例子
this.$http({
method: "get",
url: "/api/v1/dashboard/doctor/schedule/export",
params: params,
responseType: "blob"
})
.then(response => {
this.isDownload = false;
fileDownload(
response,
"",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"
);
})
.catch(error => {
this.isDownload = false;
});