前端-uniapp封装接口

第一次封装

先建目录utils/request.js,在里面放进以下代码

基地址要改成后端地址

export const baseURL = '基地址'
 
export const request = (options) => {
	return new Promise((resolve, reject) => {
		uni.request({
			url: baseURL + options.url, //接口地址:前缀+方法中传入的地址
			method: options.method || 'GET', //请求方法:传入的方法或者默认是“GET”
			data: options.data || {}, //传递参数:传入的参数或者默认传递空集合
			header: {
				'token': uni.getStorageSync("token") || "" //自定义请求头信息
			},
			success: (res) => {
				console.log(res, uni.getStorageSync('token'));
				//返回的数据(不固定,看后端接口,这里是做了一个判断,如果不为true,用uni.showToast方法提示获取数据失败)
				if (res.data.code == 1) {
					resolve(res.data.data)
				} else {
					if(res.data.code== 401){
						uni.navigateTo({
							url:'/login/login'
						})
						uni.clearStorageSync()
					}
					reject(res.data.msg)
				}
				// 如果不满足上述判断就输出数据
			},
			// 这里的接口请求,如果出现问题就输出接口请求失败
			fail: (err) => {
				console.log(err)
				reject(err)
			}
		})
	})
}

 第二次封装

先建目录api/index.js,在里面放进以下代码

import {
	request
} from '@/utils/request.js'
 
 
// 获取论坛类型 /api/forum/ftype/index
export const getForumType = (page, rows) => request({url: 'forum/ftype/index',method: 'post',data: {page,rows}})

每次接口都需要定义一下 ,然后每次使用时的时候按需引入一下

 页面使用的时候需要,这个async需要在onLoad里使用,才有快捷键,快捷键的设置方法如下图。

		onLoad() {
			async getForumType(){
			import { getForumType } from '@/api/' //这一行需要放在script下,最上面一行
			  try {
			    const res = await getForumType()
			    console.log('getForumType', res)
			    // 保存数据
			  } catch (err) {
			  uni.showToast({ title:err,icon:'none' })
			    console.log('getForumType', err)
			  }
			},
		},

  • 10
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值