前言
好记性不如烂笔头~
内容
axios封装 | request.js
import axios from "axios"; import staticPath from "../config/staticPath"; import {getConfig} from "./config"; const request = axios.create({ baseURL: staticPath.BaseApi, timeout: 20000, adapter: require('axios/lib/adapters/http') }) // 异常拦截处理器 const errorHandler = error => { error.response && console.error(`errorHandler: ${error.response.status}, ${error.response.data.message}`) return Promise.reject(error) } // 请求拦截器 request.interceptors.request.use(config => { if (!config.headers['Content-Type']) config.headers['Content-Type'] = 'application/json' // 我这里存在多种baseURL的情况,所以根据渠道来进行判断使用不同的域名 if (config.requestBase) { let configData = getConfig()xxx if (staticPath.Channel === 'channel1xxxx') config.baseURL = configData.xxx_oss_host || '' if (staticPath.Channel === 'default') config.baseURL = configData.xxxx_upload_host || '' } return config }, errorHandler) // 响应拦截器 request.interceptors.response.use(response => { if (response.data.streams && response.data.format) { return response.data } // 我这里response.data.success是结合服务端自定义的返回字段来进行判断,不涉及可以直接干掉 if (response.status !== 200 || !response.data.success) { return Promise.reject(response.data) } return response.data }, errorHandler) export default request
API封装 | api.js
import request from '../utils/request'; import fs from "fs"; const FormData = require('form-data') const Api = { getConfig : '/im/machines/new', uploadFile: '/file/upload', getFileLink: '/file/getResources', } /** * 获取小助手配置信息 * @param {object} data 请求数据 * @return {AxiosPromise} */ export function getConfigInfo(data) { return request({ url: Api.getConfig, method: 'POST', data: data }) } /** * 文件下载 * @param {string} url 文件链接地址 * @return {AxiosPromise} */ export function getFileDownloadURL(url) { return request({ url: url, method: 'GET', responseType: 'stream' }) } /** * 上传文件 * @param {string} filePath 本地文件路径 * @return {AxiosPromise} */ export function uploadMsgFile(filePath) { let formData = new FormData() formData.append('multipartFile', fs.createReadStream(filePath)) let headers = formData.getHeaders() return request({ url: Api.uploadFile, method: 'POST', data: formData, headers: headers, requestBase: true }) } /** * 获取文件下载地址 * @param {string} params 文件的KEY * @return {AxiosPromise} */ export function getFileLink(params) { return request({ url: Api.getFileLink, method: 'GET', params: params, requestBase: true }) }
使用示例
// 正常使用 import {getConfigInfo} from "../api"; getConfigInfo({...staticPath.WeComHelperInfo}).then(r => { console.log(r) }).catch(err => console.error(`getConfigInfo: 获取配置文件请求异常${JSON.stringify(err)}`)) // 下载文件 const streamWriter = fs.createWriteStream(localFile) let response = await getFileDownloadURL(url).catch(error => console.error(`getFileDownloadURL: 下载文件异常${JSON.stringify(error)}`)) response.pipe(streamWriter) streamWriter.on('finish', () => {console.log('下载完成') }) streamWriter.on('error', error => console.error(`streamWriter: 文件写入异常${error}`))
学无止境,谦卑而行.