文章目录

  • 一、请求和传递参数
    • 1、get 请求
    • 2、post 请求
    • 3、axios 请求配置
  • 二、axios 的二次封装
    • 1、配置拦截器
    • 2、发送请求
  • 三、API 的解耦
    • 1、配置文件对应的请求
    • 2、获取请求的数据
  • 四、总结

一、请求和传递参数

在 Vue 中,发送请求一般在 created 钩子中,当然放在 mounted 钩子中也没问题。

以下请求的前提都是安装了 axios,并且 import axios from 'axios' 成功导入

Axios官网链接

1、get 请求

get 请求传参,在地址里面通过 ?xxx=123 的形式

// Vue 环境中async created() {let res = await axios.get("http://testapi.xuexiluxian.cn/api/slider/getSliders?xxx=123");console.log(res);}

2、post 请求

post 请求传参,在第二个参数里面传递

// Vue 环境中async created() {let res = await axios.post('http://testapi.xuexiluxian.cn/api/course/mostNew', {pageNum: 1,pageSize: 5})console.log(res);}

3、axios 请求配置

请求配置里面可以设置很多属性

// Vue环境中async created() {let res = await axios({url: 'http://testapi.xuexiluxian.cn/api/course/mostNew',method: 'post', // 默认是 get 请求headers: {}, // 自定义请求头data: {// post 请求,前端给后端传递的参数pageNum: 1,pageSize: 5}, params: {}, // get 请求,前端给后端传递的参数timeout: 0, // 请求超时responseType: 'json' // 返回的数据类型})console.log(res);}

二、axios 的二次封装

目的:方便统一管理

注意:先安装 axios 才可以使用,终端键入:npm i axios,之后回车安装它

1、配置拦截器

在 src 目录下新建 utils 文件夹,该文件夹下创建 request.js 文件

request.js 文件

  1. 首先创建 axios 对象
  2. 添加请求拦截器(前端给后端的参数)
  3. 添加响应拦截器(后端给前端的数据)
import axios from 'axios'// 创建 axios 对象const instance = axios.create({baseURL: 'http://testapi.xuexiluxian.cn/api', // 根路径timeout: 2000 // 网络延时})// 添加请求拦截器 => 前端给后端的参数【还没到后端响应】instance.interceptors.request.use(function (config) {// 在发送请求之前做些什么return config;}, function (error) {// 对请求错误做些什么return Promise.reject(error);});// 添加响应拦截器 => 后端给前端的数据【后端返回给前端的东西】instance.interceptors.response.use(function (response) {// 对响应数据做点什么return response;}, function (error) {// 对响应错误做点什么return Promise.reject(error);});// 最终返回的对象export default instance

2、发送请求

在需要发请求的组件中,导入 request.js, 之后发送请求即可

App.vue 组件

  1. 在需要使用的组件中 导入 request
  2. 直接发送请求即可
<template><div id="app">发送请求</div></template><script>import request from "./utils/request";export default {name: "App",data() {return {};},created() {// get 请求request({url: "/course/category/getSecondCategorys",}).then((res) => {console.log(res);});// post 请求request({url: "/course/mostNew",method: "post",data: {pageNum: 1,pageSize: 5,},}).then((res) => {console.log(res);});}}</script>

三、API 的解耦

API 解耦的目的:为了同一个接口可以多次使用; 为了方便 api 请求统一管理

1、配置文件对应的请求

在 src 目录下新建 api 文件夹,该文件夹下创建 xxx.js 文件,配置对应请求

import { axios } from "@/utils/request"import requestJpaas from "../../utils/geteway"import serve from "./serve"const { getData } = requestJpaas// 服务const prefix = "/jpaas-jiop-web-server"const api = {// 获取用户信息getUserInfo: prefix + "/interface/buttjoint/jisbuttsuccess",}export const yhzxAPI = {// 获取用户信息getUserInfo(params) {return axios({url: api.getUserInfo,method: "get",params})},// 网关接口queryList(appid, interface_id, params) {return getData({appid,interface_id,params})}}

2、获取请求的数据

App.vue 组件

从文件定义的请求中导入对应函数
获取数据

<template><div></div></template><script>import { yhzxAPI } from '@/api/yhzx/yhzx.js'export default {name: 'IndexView',data() {return {}},created() {this.getRecord()},mounted() {},methods: {getRecord() {let params = {title: document.title,address: encodeURIComponent(location.href),type: 'xxxxxx',}yhzxAPI.getUserInfo(params).then((result) => {if (result.code == 200 && result.success) {console.log('我的足迹添加成功!')} else {console.log('我的足迹添加失败或未登录!')}}).catch((err) => {console.log(err)})},}}</script><style scoped lang="less"></style>

四、总结

对 axios 的二次封装,在企业级项目中是 必须 要配置的。
因为经过封装的 axios,更容易使用和管理,并且可以 减少代码量,让 逻辑更清晰