doubleyong
管理员
管理员
  • 最后登录2025-02-06
  • 发帖数1196
  • 最爱沙发
  • 喜欢达人
  • 原创写手
  • 社区居民
  • 忠实会员
阅读:479回复:0

[其它]uniapp中使用axios 的步骤

楼主#
更多 发布于:2024-11-22 14:28
uniapp中使用axios的步骤如下:
第一步:安装axios

npm i axios


注意: 如果你的uniapp项目中还没有“package.json”文件,请先初始化项目
npm init -y
第二步:下载axios配置器
npm install axios-adapter-uniapp



第三步:封装axios(request.js)
import axios from 'axios'
import axiosAdapterUniapp from 'axios-adapter-uniapp'
const ConfigBaseURL = 'https://localhost:3000/'
// 使用create方法创建axios实例
const Service = axios.create({
  baseURL: ConfigBaseURL, //1. 设置默认地址
  adapter: axiosAdapterUniapp, //axios配置器
  timeout: 7000 // 2. 请求超时时间
})
//3. 给POST请求添加请求头设置(不同项目,值不一样)
Service.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';
//4.1 添加请求拦截器
Service.interceptors.request.use(config => {
  loadingInstance = Loading.service({
    lock: true,
    text: 'loading...'
  })
  return config
})
//4.2 添加响应拦截器
Service.interceptors.response.use(response => {
  loadingInstance.close()
  // console.log(response)
  return response.data
}, error => {
  console.log('TCL: error', error)
  const msg = error.Message !== undefined ? error.Message : ''
  Message({
    message: '网络错误' + msg,
    type: 'error',
    duration: 3 * 1000
  })
  loadingInstance.close()
  return Promise.reject(error)
})
export default Service


第四步:使用axios调用接口
import axios from "@/http/request.js";
export const deleteTryListenById = (id: number) =>  axios({
    url: "/deleteTryListenById", 
   method: "POST",
    params: {      
       tryListenId: id,
    }
 });

第五步:调用写好的接口
import {
  deleteTryListenById ,
} from "@/http/Api/TryListen";
const delTryListen = async (id: number) => {
  const res = await deleteTryListenById (id);
  console.log(res);
}
知识需要管理,知识需要分享
游客


返回顶部

公众号

公众号