uniapp はリクエスト メソッドをどのようにカプセル化しますか

1,LanBowanShop/utils/request.js

import cofig from './config.js'
export default (url,data={},method='GET')=>{
	return  new Promise((resolve,reject)=>{
		uni.request({
			url:cofig.baseUrl+url,
			data,
			method,
			success(res) {
				resolve(res.data);
			},
			fail(err) {
				reject(err);
			}
		})
	})
}

2、LanBowanShop/utils/config.js:

export default {
	baseUrl: 'http://localhost:7788'
}

3、カプセル化されたリクエストメソッドをテストする

   リクエストインターフェイス: http://localhost:7788/getIndexData

<script>
	//1.导入封装好的请求数据方法
	import http from '@/untils/request.js';
	export default {
		data() {
			return {
				title: 'Hello'
			}
		},

		methods: {
			//2.请求首页数据
			async getIndexData() {
				let {
					data: res
				} = await http('/getIndexData');
				console.log(res);
			}
		},

		created() {
			// 3.在声明周期函数中使用
			this.getIndexData()
		}

	}
</script>

この時点では、アプレットは正常に実行されており、h5 ページはクロスドメインを生成します。

バックグラウンドポートはlocalhost:7788なので、

クライアントアドレス: http://localhost:8080/#/pages/index/index

つまりクロスドメイン

 

アプレットにはクロスドメインはありませんが、H5 プロジェクトの場合はクロスドメインがあります。

ルート ディレクトリに vue.config.js を作成します。

module.exports = {
  devServer: {
    proxy: {
      '/api': {
        target: 'http://localhost:7788',
        ws: true,
        changeOrigin: true,
        pathRewirte:{ //路径重写
             '^/api':''
         }
      },
      '/foo':{
          target:'http://localhost:3001'
        
      }
    }
  }
}

送信リクエストを変更します:

ページ/index.vue

// 获取首页数据
methods: {
			//2.请求首页数据
			async getIndexData() {

				// #ifdef MP-WEIXIN
				let {data:res} = await http('/getIndexData'); //小程序
				// #endif

				// #ifdef H5
				let {data:res} = await http('/api/getIndexData'); //h5
				// #endif
				console.log(res);


			}
		},

untils/request.js

import config from './config.js';
export default (url, data = {}, method = 'GET') => {
	return new Promise((resolve, reject) => {
		uni.request({
			// #ifdef MP-WEIXIN
			url: config.baseUrl + url, //小程序
			// #endif

			// #ifdef H5
			url,
			//#endif
			data,
			method,
			success: (res) => {
				resolve(res)
			},
			fail: (erro) => {
				reject(erro)
			}
		})
	})
}

 h5 でもまだ動作しない場合は、

 リクエストは成功しましたが、データは HTML 形式であることが示されています

 

 

"h5": {
		"title": "Test",
		"devServer": {
			"port": 8082,
			"disableHostCheck": true,
			"proxy": {
				"/api": {
					"target": "http://localhost:7788",
					"changeOrigin": true,
					"secure": false,
					"pathRewrite": {
						"^/api": ""
					}
				}
			}
		}
	}

このように、h5で得られるデータは正常です。

おすすめ

転載: blog.csdn.net/qq_46376192/article/details/129052283