当前位置: 首页>后端>正文

vue3+uniapp配置axios

1.下载axios包

npm install axios axios-miniprogram-adapter
yarn add axios axios-miniprogram-adapter

2.创建utils/request.js文件

import { userStore } from '@/store/user'
import { storeToRefs } from 'pinia'
const store = userStore();
const {token} = storeToRefs(store);
// axios二次封装
// yarn add axios-adapter-uniapp import axiosAdapterUniapp from 'axios-adapter-uniapp'

import axios from "axios";
// 小程序axios适配器
import mpAdapter from "axios-miniprogram-adapter";
axios.defaults.adapter = mpAdapter;
// import { toast, showConfirm, tansParams } from "@/utils/common";
 
//根据环境变量获取api地址
// let baseURL = process.env.config[process.env.UNI_SCRIPT].VITE_BASE_API;
const baseURL = import.meta.env.VITE_API_BASE_URL
// let evnName = process.env.config[process.env.UNI_SCRIPT] 获取当前处于哪个开发环境
console.log("baseURL:", baseURL);
 
class HttpRequest {
  constructor() {
    this.baseURL = baseURL; // 从环境变量中获取api地址
    this.timeout = 300000;
  }
  mergeOptions(options) {
    return {
      baseURL,
      timeout: 300000,
      ...options,
    };
  }
  request(options) {
    const instance = axios.create();
    this.setInterceptors(instance);
    const opts = this.mergeOptions(options);
    return instance(opts);
  }
  get(url, data = {}, outHeaders = {}) {
 
    return this.request({
      dataType: "json",
      method: "get",
      url,
      params: { ...data }, // get参数可以直接展开
      headers: {
      },
    });
  }
  post(url, data = {}, outHeaders = {}) {
    // 请求体中 {}
    return this.request({
      method: "post",
      url,
      data, // post要求必须传入data属性
      headers: {
      },
    });
  }
 
  // 设置拦截器
  setInterceptors(instance) {
    // 请求拦截器
    instance.interceptors.request.use(config => {
        //添加请求头
        config.headers["qlm-jwt"] = token.value;
        console.log('请求拦截成功',token)
        
        return config;
    },
    error => {
        console.log(error); // for debug
        return Promise.reject(error);
    }
    );
    // 响应拦截器
    instance.interceptors.response.use(
      (res) => {
        const noLoading = res.config.headers["NO-LOADING"];
        if (!noLoading) {
          uni.hideLoading();
        }
        let { data } = res;
        // console.log("请求获取data", data)
        if (data) {
          if (data.retCode === 88888888) {
            //console.log('data=============', data)
            return Promise.resolve(data);
          } else {
            // showConfirm({
            //   content: data.msg,
            //   showCancel: false,
            // }).then((res) => {
            //   /*               if (res.confirm) {
            //     store.dispatch("LogOut").then((res) => {
            //       uni.reLaunch({ url: "/pages/login" });
            //     });
            //   } */
            // });
            return Promise.resolve(data);
          }
        }
      },
      (err) => {
        console.log("axios报错", err);
        uni.hideLoading();
        return Promise.reject(err);
      }
    );
  }
}
 
export default new HttpRequest();

3.在src目录下创建src/api/config文件夹

vue3+uniapp配置axios,第1张

config文件夹中创建login.js文件,登录的接口都放在里面统一管理

export default {
  verifyCode: "/usermanager/verifyCode",
  getJobFairListNoPage:'/zRecruit/jobfair/getJobFairListNoPage',
  loginfrom:'/usermanager/login'
}

和config文件夹同级创建login.js文件,统一管理请求接口的方法

import axios from '@/utils/request.js'
import login from './config/login'

export const verifyCode = () => axios.get(login.verifyCode)// 获取验证码
export const loginfrom = b => axios.post(login.loginfrom,b)
export const getJobFairListNoPage = b => axios.post(login.getJobFairListNoPage, b)

4.页面中使用

<template>
    <view class="footer">
      <button class="action-btn" @click="goApply">测试接口</button>
        <view class="uni-form-item uni-column">
        <view class="title">账号</view>
            <input  v-model="loginForm.loginName" class="uni-input" type="number" placeholder="账号"/>
        </view>
        <view class="uni-form-item uni-column">
            <view class="title">密码</view>
            <input v-model="loginForm.password" class="uni-input" password type="text" placeholder="密码" />
        </view>

        <view class="uni-form-item uni-column">
            <view class="title">验证码</view>
            <input v-model="loginForm.code" class="uni-input" confirm-type="search" placeholder="验证码" />
        </view>
        <view class="uni-btn-v">
            <button form-type="submit" @click="loginceshi">登录</button>
            <!-- <button type="default" form-type="reset">Reset</button> -->
        </view>
        <view class="user-img">
            <button class="action-btn" @click="getCode">验证码</button>
            <image :src='src'></image>
        </view>
        <view class="">
            {{token}}
        </view>
    </view>
</template>


<script setup>
import { onLoad, onReady } from '@dcloudio/uni-app'
import { ref,onMounted } from 'vue'
import { getuuid } from '@/utils/qlm_commonfuns.js'
import { getJobFairListNoPage,verifyCode,loginfrom } from '@/api/login'

let code = ref({})
let loginForm = ref({
    version:"1.0",
    consumer:'zRecruit-Person-PC',
    serialNo:getuuid(),
    language:'zh_cn',
    loginName: '18911996282',
    // password: md5.hex_md5('123456'),
    password:'e10adc3949ba59abbe56e057f20f883e',
    code: '',
    codeID: ''
})

async function loginceshi() {
    const res = await loginfrom(loginForm.value)
    console.log('res',res)
    const test = userStore()
    test.setToken(res.data)
    }
// 测试
  async function goApply() {
      // const { actId, orgId } = form.value
    const params = {
      consumer:'zRecruit-Person-PC',
      serialNo:getuuid(),
      // serialNo: '583b4270-bbfe-11ee-bfdc-a5d164265181',
      page: 1,
      size:10,
      total: 10,
      companyId: '2c9101e48d3fb558018d409a8c070000',
      fairAddress: "",
      fairAtt: "",
      fairContact: "",
      fairDate: "",
      fairIntro: "",
      fairName: "",
      fairNoticeID: "",
      fairPhone: "",
      fairid: "",
      status: "2",
      statusDes: "",
      applyStatus: ""
    }
      const res = await getJobFairListNoPage(params)
      console.log('res',res)

}

// 获取图形验证码
function getCode() {
    verifyCode().then((res) => {
        console.log(res.data, 'res')
        src.value=res.data.img
        // code=res.data
        loginForm.value.codeID=res.data.id
    })
}
</script>

请求成功:


vue3+uniapp配置axios,第2张

https://www.xamrdz.com/backend/3um1936601.html

相关文章: