Vue disguises the backend to respond to frontend requests - the installation and use of mockjs

  1. What is the mockjs library

The mockjs library is used when the back-end staff does not request an interface for you, but you have already done this part of the function and need to test it. With mockjs, you can intercept the ajax request and send the fake data we defined in advance back to the local response just request

  1. Installation and introduction of mockjs

  • Create a mock folder under the src folder. Under the mock folder, you need to create a js forget to set the path to send data

  • Finally, you need to import the js file in the mock into main.js to use the mock

在终端下载mockjs
npm i mockjs
// 引入MockServer.js 【mock虚拟数据】
import '@/mock/mockServer'
  • Create two types of files under the mock folder, one with a json suffix, to fill in the fake data you sent, as shown below

  • Of course, there is also the js file mentioned earlier. In this file, we need to import the mockjs library, and then import the prepared fake data json file. Finally, we need to set the path, request status and data.

We need to introduce fake data into the js file and set his request address and request data
// 先引入mockjs模块
import Mock from 'mockjs';
// 把JSON 数据格式引入进来【JSON数据格式根本没有对外暴露,但是可以引入】
// todo webpack默认对外暴露:图片、JSON数据格式
import banner from './banner.json'

// ?mock数据:第一个参数请求地址,第二个参数:请求数据
Mock.mock('/mock/banner', { code: 200, data: banner })

  1. send request

Create a mock simulation data request file under the request data folder api, and the file request code is placed below
// todo 这是个模拟数据的请求文件

// 对于axios 进行二次封装
import axios from 'axios'

// * 1、利用axios 对象的方法 create,去创建一个axios实例
// * 2、requests 就是axios,只不过稍微配置一下
const requests = axios.create({
    // todo 配置对象

    // ? 基础路径,即向http://xxx.xxx.8080发请求时,后面都会带有 [/api] 的路径
    baseURL: '/mock',

    // ? 代表请求时间超时的时间是:5s
    timeout: 5000,
})

// todo 3.1、请求拦截器:在发送请求之前,请求拦截器可以检测到,可以在请求发出去之前做一些事情
requests.interceptors.request.use((config) => {
    // ? config: 配置对象,对象里面有一个属性很重要,header请求头
    return config
})

// todo 3.2、响应拦截器:服务器响应数据回来以后,拦截器可以检测到,可以做一些事情
requests.interceptors.response.use((res) => {
    // * 响应成功的回调函数
    return res.data
}, (error) => {
    // * 响应失败的回调函数
    return Promise.reject(new Error('faile'))
})

// *对外暴露
export default requests
  • Now the data can be sent, here I set the sending function, and then request in vuex

  1. important point

Our fake data and image resources must be in the public folder so that they can be used

In it, we need to create a folder dedicated to placing pictures, the images folder

Guess you like

Origin blog.csdn.net/weixin_49931650/article/details/129462161