vue 这种流数据如何获取?

控制台打印的response:
vue 这种流数据如何获取?
但是我却获取不到这个data,断点打印的res是个空对象
vue 这种流数据如何获取?
公共方法:

export const createExcel = (res, name) => {

let blob = new Blob([res], {

type: 'application/vnd.ms-excel',

});

let fileName = name + '.xlsx'; // 文件名+后缀

// 允许用户在客户端上保存文件

if (window.navigator.msSaveOrOpenBlob) {

navigator.msSaveBlob(blob, fileName);

} else {

// eslint-disable-next-line no-debugger

debugger;

var link = document.createElement('a'); //定义一个a标签

link.href = window.URL.createObjectURL(blob); //需要生成一个 URL 来实现下载,链接到blob上

link.download = fileName; //下载后的文件名称

console.log('fileName', link);

link.click(); //模拟在按钮上实现一次鼠标点击

window.URL.revokeObjectURL(link.href); //释放 URL 对象

}

};

页面调用

getOrganExport({ parentId: this.nodeId })

.then((res) => {

console.log('res----', res);

createExcel(res, '组织管理表');

this.$message.success('导出成功');

})

.catch(() => {

this.$message.error('导出失败,请稍后再试');

});

service封装:

import axios from 'axios';

import qs from 'qs';

import { Message } from '@jdt/find';

// import Cookies from 'js-cookie';

const defaultOptions = {

baseURL: '/api',

method: 'post', // 请求 type get post delete header put

withCredentials: true, // 设置该属性可以把 cookie 信息传到后台

headers: {

Accept: 'application/json',

'Content-Type': 'application/json; charset=utf-8',

},

};

const http = axios.create(defaultOptions);

http.interceptors.request.use(

(config) => {

// 在发送请求之前做些什么

const { method, data, headers, baseURL } = config;

// 如果参数中有baseURL‘,更新默认baseURL

if (baseURL && baseURL === process.env.VUE_APP_BASE_URL) http.baseURL = baseURL;

if (method !== 'get' && method !== 'head') {

if (data instanceof FormData) {

config.data = data;

// config.headers = {

// ...headers,

// 'x-requested-with': 'XMLHttpRequest',

// 'cache-control': 'no-cache',

// };

delete config.headers;

} else if (headers['Content-Type'] === 'application/x-www-form-urlencoded') {

config.data = qs.stringify(data);

} else {

// 是否需要去除无用数据

// Object.keys(data).forEach((item) => {

// if (data[item] === null || data[item] === undefined || data[item] === '') {

// delete data[item];

// }

// });

config.data = JSON.stringify(data);

}

}

if (method === 'get') {

config.paramsSerializer = function (params) {

return qs.stringify(params, {

arrayFormat: 'indices',

});

};

}

return config;

},

(error) => {

// 对请求错误做些什么

return Promise.reject(error);

}

);

http.interceptors.response.use(

(response) => {

console.log(response);

const { data: { data, status = true, error = {} } = {} } = response;

if (!status) {

const msg = error.msg || '服务端执行出错!';

if (error.code === 'REL001') {

return Promise.reject(msg);

} else {

Message.error(msg);

}

return Promise.reject(msg);

}

return data || {};

},

(error) => {

if (error.response) {

// The request was made and the server responded with a status code

// that falls out of the range of 2xx

const { status: responseStatus } = error.response;

if (responseStatus === 401) {

// 记录当前跳出登录地址,登录成功后跳回来

// Cookies.set('origin_url', window.location.href);

// window.location = '/login';

} else if (responseStatus === 403) {

// 没有权限

Message.error('没有权限操作!');

} else {

const msg = error.response?.data?.error?.msg || '服务端接口异常!';

Message.error(msg);

return Promise.reject(new Error(msg));

}

} else {

// Something happened in setting up the request that triggered an Error

console.error(error);

return Promise.reject(new Error('请求出错!'));

}

return Promise.reject(error);

}

);

export default http;


回答:

你的res来自于response.data.data,可是实际上你的文件流数据的位置是response.data


比如你可以这样修改,仅供参考

service.interceptors.request.use(

(config) => {

if(config.noverify){

config.headers["noverify"] = true

delete config.noverify

}

return config;

},

(error) => {

// 发送失败

Promise.reject(error);

}

);

service.interceptors.response.use(

(response) => {

console.log(response);

let noverify = response.config.headers.noverify

if (noverify) {

const { data } = response;

retrun data

}else{

const { data: { data, status = true, error = {} } = {} } = response;

if (!status) {

const msg = error.msg || '服务端执行出错!';

if (error.code === 'REL001') {

return Promise.reject(msg);

} else {

Message.error(msg);

}

return Promise.reject(msg);

}

return data || {};

}

}

},

(error) => {

return Promise.reject(error);

}

);

使用的时候就是

http({

url: "xxx",

method: "post",

noverify: true

})


回答:

import axios from 'axios'

import { saveAs } from 'file-saver'

import { Notification, MessageBox, Message, Loading } from 'element-ui'

const service = axios.create({

// axios中请求配置有baseURL选项,表示请求URL公共部分

baseURL: process.env.VUE_APP_BASE_API,

// 超时

timeout: 100000

})

const tansParams = (params) => {

let result = ''

for (const propName of Object.keys(params)) {

const value = params[propName];

var part = encodeURIComponent(propName) + "=";

if (value !== null && value !== "" && typeof (value) !== "undefined") {

if (typeof value === 'object') {

for (const key of Object.keys(value)) {

if (value[key] !== null && value !== "" && typeof (value[key]) !== 'undefined') {

let params = propName + '[' + key + ']';

var subPart = encodeURIComponent(params) + "=";

result += subPart + encodeURIComponent(value[key]) + "&";

}

}

} else {

result += part + encodeURIComponent(value) + "&";

}

}

}

return result

}

const blobValidate = async (data) => {

try {

const text = await data.text();

JSON.parse(text);

return false;

} catch (error) {

return true;

}

}

export function download(url, params, filename) {

downloadLoadingInstance = Loading.service({ text: "正在下载数据,请稍候", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", })

return service.post(url, params, {

transformRequest: [(params) => { return tansParams(params) }],

headers: { 'Content-Type': 'application/x-www-form-urlencoded' },

responseType: 'blob'

}).then(async (data) => {

const isLogin = await blobValidate(data);

if (isLogin) {

const blob = new Blob([data])

saveAs(blob, filename)

} else {

const resText = await data.text();

const rspObj = JSON.parse(resText);

console.log(resObj)

}

downloadLoadingInstance.close();

}).catch((r) => {

console.error(r)

Message.error('下载文件出现错误,请联系管理员!')

downloadLoadingInstance.close();

})

}

这是我项目中的将文件流下载到本地的方法 你可以参考一下

以上是 vue 这种流数据如何获取? 的全部内容, 来源链接: utcz.com/p/933152.html

回到顶部