[uniapp] uniapp インターフェイスのパッケージ化とパッケージ化の最適化:


1. uniapp に付属の uni.request と uni.uploadFile を使用します。

ここに画像の説明を挿入

let BASE_URL = ''
BASE_URL = process.env.NODE_ENV == 'development' ? '/kd' : 'https://yun.kldhq.com'  // '/kd'为代理

const http = (api, method, param, contentType) => {
    
    
	return new Promise((resolve, reject) => {
    
    
		uni.showLoading({
    
     title: '加载中~' });
		uni.request({
    
    
			url: BASE_URL + api,
			method: method || 'GET',
			data: param,
			params: param,
			header: {
    
    
				'Content-Type': contentType || 'application/x-www-form-urlencoded',
				'token': uni.getStorageSync('GuangQiPhotoUploadToken')
			},
			dataType: 'json',
			success: (response) => {
    
    
				resolve(response)
			},
			fail: (error) => {
    
    
				uni.showModal({
    
     title: '提示', content: '网络连接错误:' + error, showCancel: false });
				reject(error)
			},
			complete: () => {
    
    
				uni.hideLoading();
			}
		});
	})
}

const httpUploadFile = (api, flieList, param) => {
    
    
	return new Promise((resolve, reject) => {
    
    
		uni.showLoading({
    
     title: '加载中~' });
		uni.uploadFile({
    
    
			url: BASE_URL + api,
			files: flieList,
			formData: param,
			header: {
    
    
				"token": uni.getStorageSync('GuangQiPhotoUploadToken')
			},
			success: (response) => {
    
    
				resolve(response)
			},
			fail: (error) => {
    
    
				uni.showModal({
    
     title: '提示', content: '图片上传失败:' + error, showCancel: false });
				reject(error)
			},
			complete: () => {
    
    
				uni.hideLoading();
			}
		});
	})
}

export {
    
     http, httpUploadFile }

ここに画像の説明を挿入

import {
    
     http, httpUploadFile } from '@/utils/http.js'
Vue.prototype.$http = http
Vue.prototype.$httpUploadFile = httpUploadFile

ここに画像の説明を挿入
ここに画像の説明を挿入
ここに画像の説明を挿入

次に、axios を使用します。

npm i axios

ここに画像の説明を挿入
ここに画像の説明を挿入

let BASE_URL = ''

if (process.env.NODE_ENV == 'development') {
    
    
	BASE_URL = 'http://192.168.8.237:8002' // 开发环境
} else {
    
    
	BASE_URL = 'https://yun.kldhq.com' // 生产环境
	console.log = () => {
    
    }
}

export default BASE_URL

ここに画像の説明を挿入

import axios from 'axios'
import BASE_URL from './config.service.js'


// 创建axios对象
const request = axios.create({
    
    
	baseURL: BASE_URL,
	// 跨域请求是否提供凭据信息(cookie、HTTP认证及客户端SSL证明等),也可以简单的理解为,当前请求为跨域类型时是否在请求中协带cookie。
	// 注意:withCredentials和后端配置的cros跨域不可同时使用
	//withCredentials: true, 
	// 请求超时时间
	timeout: 10000,
	// 是否跨域请求
	crossDomain: true,
	// headers:{
    
    
	// 	"Content-Type":"application/json;charset:utf-8",
	// },
	headers: {
    
    
		"Content-Type": "multipart/form-data",
	},
})

// request拦截器,在请求之前做一些处理
request.interceptors.request.use(config => {
    
    
	//请求时显示正在加载中
	uni.showLoading({
    
     title: '加载中~' });
	//添加请求头,比如从本地缓存获取token
	if (uni.getStorageSync("GuangQiPhotoUploadToken")) {
    
    
		config.headers['token'] = uni.getStorageSync('GuangQiPhotoUploadToken')
	}
	return config;
}, error => {
    
    
	return Promise.reject(error);
});

// 配置成功后的拦截器
request.interceptors.response.use(response => {
    
    
	//请求时成功后关闭正在加载中
	uni.hideLoading();
	if (response.data.code == 0) {
    
    
		return response
	} else {
    
    
		uni.showToast({
    
     title: response.data.message || response.data.msg, duration: 2000, icon: 'none' })
		return Promise.reject(response.data.message || response.data.msg);
	}
}, error => {
    
    
	return Promise.reject(error)
})

export default request

ここに画像の説明を挿入

import axios from 'axios'

// 在main.js中放入这段自定义适配器的代码,就可以实现uniapp的app和小程序开发中能使用axios进行跨域网络请求,并支持携带cookie
axios.defaults.adapter = function(config) {
    
    
	return new Promise((resolve, reject) => {
    
    
		let settle = require('axios/lib/core/settle');
		let buildURL = require('axios/lib/helpers/buildURL');
		uni.request({
    
    
			methods: config.methods.toUpperCase(),
			url: config.baseURL + buildURL(config.url, config.params, config.paramsSerializer),
			header: config.headers,
			data: config.data,
			dataType: config.dataType,
			responseType: config.responseType,
			sslVerify: config.sslVerify,
			complete: function complete(response) {
    
    
				response = {
    
    
					data: response.data,
					status: response.statusCode,
					errMsg: response.errMsg,
					header: response.header,
					config: config
				};
				settle(resolve, reject, response);
			}
		})
	})
}


// axios请求
import request from '@/utils/service/service.js'
Vue.prototype.$axios = request

3. パッケージの最適化とクロスドメイン プロキシ:

ここに画像の説明を挿入
ここに画像の説明を挿入

const webpack = require('webpack')
const CompressionPlugin = require('compression-webpack-plugin');

module.exports = {
    
    
	productionSourceMap: false, // 生产打包时不输出map文件,增加打包速度
	// 开发服务器配置
	devServer: {
    
    
		port: 9100,
		hot: true,
		disableHostCheck: true,
		compress: true, //压缩静态文件
		overlay: {
    
    
			warnings: false,
			errors: true,
		},
		// headers: {
    
    
		//   'Access-Control-Allow-Origin': '*',
		// },
		proxy: {
    
    
			'/kd': {
    
    
				target: 'http://192.168.8.237:8002',
				ws: false,
				secure: true, // 如果是https接口,需要配置这个参数
				changeOrigin: true, //是否跨域
				pathRewrite: {
    
    
					'/kd': '' //默认所有请求都加了jeecg-boot前缀,需要去掉
				}
			},
		}
	},
	configureWebpack: config => {
    
    
		//生产环境取消 console.log
		if (process.env.NODE_ENV === 'production') {
    
    
			config.optimization.minimizer[0].options.terserOptions.compress.drop_console = true
		}
	},
	chainWebpack: (config) => {
    
    
		//只保留中文语言包
		config.plugin('ContextReplacementPlugin').use(webpack.ContextReplacementPlugin, [/moment[/\\]locale$/,
			/zh-cn/
		])

		//生产环境,开启js\css压缩
		if (process.env.NODE_ENV === 'production') {
    
    
			config.plugin('compressionPlugin').use(new CompressionPlugin({
    
    
				test: /\.(js|css|less)$/, // 匹配文件名
				threshold: 10240, // 对超过10k的数据压缩
				deleteOriginalAssets: false // 不删除源文件
			}))

			config.plugin('chunkPlugin').use(webpack.optimize.LimitChunkCountPlugin, [{
    
    
				maxChunks: 5,
				minChunkSize: 10000
			}])
		}

		// 配置 webpack 识别 markdown 为普通的文件
		config.module
			.rule('markdown')
			.test(/\.md$/)
			.use()
			.loader('file-loader')
			.end()
	},
}

ここに画像の説明を挿入

おすすめ

転載: blog.csdn.net/weixin_53791978/article/details/129300537