企業の開発プロジェクトに適した uniapp インターフェイスをカプセル化するために手を携えてください。

1. 新しい request.js

ディレクトリ内に共通ファイルを新規作成し、その配下に request.js を新規作成します。ディレクトリ構造は次のとおりです:
common/request.js
ここに画像の説明を挿入

request.js に次のように記述します。

var baseUrl = 'http://localhost:9999' //基本路径

//接口封装
function request(datas) {
    
    
	//Promise 异步编程的一种解决方案
	var promise = new Promise((resolve, reject) => {
    
    
		uni.request({
    
    
			url: baseUrl + datas.url,
			data: datas.data || {
    
    },
			method: datas.method || 'GET',
			header: {
    
    
				'Authorization':'Bearer '+ datas.Authorization,  //token
				'content-type': datas.type ||
					'application/json;charset=UTF-8', //内容类型(默认 application/json;charset=UTF-8)
			},
			success: function(res) {
    
    
				resolve(res) 
			},
			fail: function(err) {
    
    
				console.log(err)
				reject(err)
			}
		})
	})
	return promise;
}
module.exports = request;

2. main.jsに導入

import request from "common/request.js"//封装接口请求

Vue.prototype.requestfs=request  //封装接口请求

注: Vue.prototype.requestfs=request の requestfs は、将来のプロジェクトで axios を呼び出すために使用されます。使用法を参照してください。

3. axios を実際に使用する

テンプレートを使用する

次のコード インターフェイスをメソッド内で直接使用し、実際のインターフェイス パスとパラメーターを入力します。
Vue.prototype.requestfs=request //encapsulation インターフェイスリクエストという文はencapsulation 中に書かれているため、axios を呼び出すときにthis.requestfsを直接使用できます。

this.requestfs({
    
    
	url: '',//填写请求路径
	data: '',//填写参数(看后端是什么传参方式)
	method: "POST", //填写请求,GET默认不写本行代码
	Authorization: this.token, //填写token (看接口请求是否需要传token)
}).then(res => {
    
    
	//if (res.data.msg == "success") {  //根据后端返回数据判断
		console.log("请求成功",res)
	//}
})

使用例

1. GET リクエストを例として、最も単純なリクエスト データ レンダリング リストを取り上げます。

カプセル化する場合、デフォルトは GET リクエストであるため、メソッドにリクエスト パス URL を入力するだけで済みます。
ここに画像の説明を挿入

onShow() {
    
    
	this.getHot()
},
methods: {
    
    
	getHot() {
    
    
		this.requestfs({
    
    
			url: '/mall/goods/selectHotList?type=' + ''
		}).then(res => {
    
    
			if (res.data.msg == "success") {
    
    
				this.productsList = res.data.data
			}
		})
	},
}

2. GET リクエストを例に挙げると、トークンが必要です

ここに画像の説明を挿入

onShow() {
    
    
	var bs = uni.getStorageSync('UserInformation')
	this.token = bs.usertoken
	this.getData()
},
methods: {
    
    
	getData() {
    
    
		this.requestfs({
    
    
			url: '/mall/customer/address/selectAddress',
			Authorization: this.token,
		}).then(res => {
    
    
			this.data = res.data.data
		})
	},
}

3. POSTリクエストを例に挙げると、パラメータとトークンを渡す必要があります。

ここに画像の説明を挿入

おすすめ

転載: blog.csdn.net/qq_51463650/article/details/131535276