Axios二次封装Springboot接口

本文介绍了如何在Vue项目中使用Axios进行二次封装,以便更高效地调用SpringBoot后端接口。首先,创建utils文件夹,编写request.js以配置Axios实例并设置拦截器,然后在api.js中定义接口。接着,在Vue组件中按需导入接口并调用。此外,还展示了如何将接口路径集中管理在base.js中,并通过全局引用的方式简化调用。这样不仅提高了代码复用性,也使得接口管理更加规范。
摘要由CSDN通过智能技术生成

Axios二次封装Springboot接口

后端接口:

1、简单的分页查询

@ApiOperation(value = "查询所有问题")
@GetMapping("/findQuestion")
public Result findQuestion(Question question,
                           @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                           @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
    Page page = new Page<>(pageNo, pageSize);
    Page pageData = questionService.page(page);
    return ResultUtil.success(pageData);
}

2、Postman测试结果

在这里插入图片描述

前端Axios接口封装:

一、url直接写在axios方法中

1、在src下新建一个utils文件夹

在这里插入图片描述

2、request.js
// axios 二次封装
import axios from 'axios'

// 利用axios对象的方法create,去创建一个axios实例
// request就是axios,配置替换了
const requests = axios.create({
  baseURL: '/api',
  timeout: 5000, // 5s请求超时
})

// 请求拦截器:在发请求之前,请求拦截器可以检测到
requests.interceptors.request.use((config) => {
  // config:配置对象,对象里面有一个属性很重要,headers请求头
  return config
})

// 响应拦截器
requests.interceptors.response.use(
  (res) => {
    //成功的回调函数:服务器响应数据回来后,响应拦截器可以检测到
    return res.data
  },
  (error) => {
    return Promise.reject(new Error('faile'))
  }
)
// 对外暴露
export default requests
3、api.js(如果按照不同的模块管理接口,也可以创建多个对应的js)
import requests from './request'

export const findQuestion = (params) => {
  return requests({
    url: '/question/findQuestion',
    method: 'get',
    params,
  })
}
4、vue页面引入

按需导入就好,前面const后面跟的名字就是接口的名字

import { findQuestion } from '@/utils/api'

/**
  * 试题列表
  */
// http为方法的名字,调用接口直接  接口名字({参数名,参数值}).then((res)) => {具体实现}
 http(pageNo) {
      findQuestion({
        pageNo,
        pageSize: 10,
      }).then((res) => {
        this.tableData = res.data.records
        this.total = res.data.total
        this.pageSize = res.data.size
        this.pageNo = res.data.current
      })
    },
5、试题列表页面展示

在这里插入图片描述

6、网络请求

在这里插入图片描述

二、url封装到base.js中,$api全局引用

1、将所有接口路径都写在base.js中统一管理
const base = {
  qnyhost: 'http://rh7d40xle.hn-bkt.clouddn.com/',
  addGoods: '/project/addProject', //添加商品
  deleteGoods: '/project/deleteProjectById', // 根据id删除商品
  updateGoods: '/project/updateById' // 根据id修改商品
}

export default base
2、axios接口写在index.js中(也可以按照模块分离)

这种方法可以让所有的接口路径统一管理,再次解耦合,同时可以不需要写回调函数 .then (res)=> {…},在方法调用的时候再写回调以适用不同的需求

( base.js 和 request.js必须导入 )

/**
 * 请求的方法
 */

// 这两个依赖必须导入!!!
import base from './base'
import axios from '../utils/request'

const api = {
  /**
   * 添加商品
   * 参数: title cid  category sellPoint price num desc paramsInfo image
   */
  addGoods(params) {
    return axios.post(base.addGoods, params)
  },

  /**
   * 根据id删除商品
   * @param {*} params 
   * @returns 
   */
  deleteGoods(params) {
    return axios.delete(base.deleteGoods,{params})
  },

  /**
   * 根据id编辑商品
   * @param {*} params 
   */
  updateGoods(params) {
    return axios.put(base.updateGoods, params)
  }
}

export default api
3、全局引用组件

在main.js下引用

// 全局引用api
import api from './utils/index'
Vue.prototype.$api = api
4、使用

params作为参数传递拼接在url上时,需要用{},详细使用可以参考axios官方文档。

// POST请求
if(this.title === "添加商品"){  // 此时确认页面为添加商品页面
    this.$api.addGoods(
        // params
        this.goodsForm
    ).then(res=>{
        console.log(res)
        if(res.code===200)
        {
            this.$message({
                showClose: true,
                message: '商品添加成功',
                type: 'success',
            })
            this.$parent.http(1); // 更新父组件数据 
            // 添加成功 页面关闭
            this.clearForm();
        } else {
            // 添加失败 请重新输入
            this.$message.error('商品添加失败,请重新输入');
        }
    })
    
// DELETE请求
this.$api
        .deleteGoods({  // params作为参数传递拼接在url上时,需要用{}
        id: row.id,
    })
        .then((res) => {
        if (res.code === 200) {
            this.$message({
                type: "success",
                message: "删除成功!",
            });
            // 视图更新
            this.http(1);
        } else {
            // 删除失败 
            this.$message.error('商品删除失败');
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值