Axios request encapsulation of Vue (modified version)

When using Vue to develop our projects, it is bound to be used router, and it may be used vuex, but we will definitely use it axios. For beginners, we basically use it and main.jsimport it directly. But when we are actually doing projects, we all need to axiosencapsulate requests. For example, our requests need to be carried token, or we have multiple environments: such as test environment, development environment, etc...
Here we mainly record axiosthe simple encapsulation.

1. Preparation stage

Initialization project

⭐ Installing Vue will not be discussed here. Let’s recreate a Vueproject to start.

Vue create my-project

cd my-project # 进入项目目录
yarn # 安装依赖,也可以使用 npm install
yarn serve # 启动项目

Install axios

⭐After the project is created, we start the installation axios.

yarn add axios -S

-D: Short for --save-dev, the module writes to devDependenciesthe object.

  • devDependenciesObjects are some packages that we need to use during development. They are only used in the development phase. These packages are not needed when the package is actually put online, because these tools are only used by you to package the code.

-S: Short for --save, the module writes to dependenciesthe object.

  • If you need to publish it to the production environment, for example, if you want to run a vueproject based on vue.js, you need vue.jsto support it. The vue.js file needs to follow the project to the final production environment.

2. Introduction of axios

Simple introduction

axios⭐ As mentioned above, we can use it directly after installation .

  1. Import axios in main.js

    import axios from 'axios'
    // 全局挂载
    Vue.prototype.$axios = axios
    // 设置默认路由前缀
    axios.defaults.baseURL = 'http://localhost:8080'
    new Vue({
          
          
        axios,
        router,
        store,
        render: h => h(app)
    }).$mount('#app')
    
  2. .vueuse in file

    <script>
        methods:{
            Login () {
                this.$axios({
                    url:'/login',
                    method: 'post',
                    data:{
                        userName:'xxxx',
                        password:'xxxx'
                    }
                }).then((res)=>{
                    console.log(res)
                })
            }
        }
    </script>
    

3. Encapsulate axios request

⭐ We do not main.jsimport in .

1. Configure the interface base addresses required for different environments in the root directory

  1. .env global default configuration file, which will be loaded and merged regardless of the environment.

  2. .env.development Configuration file in development environment

  3. .env.production Configuration file in production environment

  4. .env.local local development environment configuration

  5. Naming rules:

    1. The attribute name must start with VUE_APP_, such as VUE_APP_XXX

      # 本地开发环境配置(.env.local)
      NODE_ENV=development
      
      # base url
      VUE_APP_API_BASE_URL=http://xx.xx.xx.xxx:8080/xxx
      VUE_APP_FORM_BASE_URL=http://xx.xx.xx.xxx:8080/xxx
      VUE_APP_SIGN_OFF_BASE_URL=http://xx.xx.xx.xxx:8080/xxx
      VUE_APP_LOGIN_BASE_URL=http://xx.xx.xx.xxx:8080/xxx
      VUE_APP_SSO_BASE_URL=http://xx.xx.xx.xxx:8080/xxx
      
      // 測試服client-id
      # VUE_APP_SSO_CLIENT_ID=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
      // 本地client-id
      VUE_APP_SSO_CLIENT_ID=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
      VUE_APP_FILE_SERVER_BASE_URL=http://xx.xx.xx.xxx:8080/xxx
      

2. Encapsulate request base file

⭐ Created in the src directorysrc/tools/http/request.js

// src/tools/http/request.js
import axios from 'axios'
import {
    
     Message} from 'element-ui' // 引入 Element 组件

export default function request ({
    
     type='COMMOn',data }){
    
    
    let baseUrl = process.env.VUE_APP_API_BASE_URL // 这是配置的 .env 文件
    switch (type) {
    
    
            case 'COMMON':
            baseUrl = process.env.VUE_APP_API_BASE_URL
            break;
            case 'LOGIN':
            baseUrl = process.env.VUE_APP_LOGIN_BASE_URL
            break;
            case 'FROM':
            baseUrl = process.env.VUE_APP_FORM_BASE_URL
      	    break;
        default:
            break;
    }
    console.log('baseUrl', process.env)
    const service = axios.create({
    
    
        baseURL: baseUrl,
        timeout: 5000
    })
    // 请求拦截器
    service.interceptors.request.use(config => {
    
    
        //发请求前做的一些处理,数据转化,配置请求头,设置token,设置loading等,根据需求去添加
        config.data = JSON.stringify(config.data); //数据转化,也可以使用qs转换
        config.headers = {
    
    
            'Content-Type':'application/x-www-form-urlencoded' //配置请求头
        }
        //注意使用token的时候需要引入cookie方法或者用本地localStorage等方法,推荐js-cookie
        const token = getCookie('名称');//这里取token之前,你肯定需要先拿到token,存一下
        if(token){
    
    
            config.params = {
    
    'token':token} //如果要求携带在参数中
            config.headers.token= token; //如果要求携带在请求头中
        }
        return config
    }, error => {
    
    
        Promise.reject(error)
    })
    
    // 响应拦截器
    service.interceptors.response.use(response => {
    
    
        return response
    }, error => {
    
    
        Message.error(error.message)
        return Promise.resolve(error.response)
    }
    return service(data)
}

4. Request data

1. Create apia folder

srcCreate apia folder in the directory and place the method of each request module. All future requests will be written under this folder. For example, our system has a role configuration module.

  1. createsrc/api/role-config.js

  2. // src/api/role-config.js
    import request from '@/tools/http/request'
    
    // 获取角色列表的 api
    export function getRoleListsApi (data) {
          
            // 接口需要的 data 数据
        return request ({
          
          
            data:{
          
          
                url:'/roleList',
                method:'post',
                data
            }
        })
    }
    

3. Introduce request api

  1. Role.vueComponent requests data

    <script>
        import { getRoleListsApi } from '@/api/role-config.js'
        export default {
            name: 'Role',
            data (){
                return {
                    roleList: [] // 存储需要渲染的数据
                }
            },
            methods:{
                // 获取角色列表
                async getRoleList () {
                    const obj = { roleid:'普通会员' }
                    const { roleList, code } = await getRoleListsApi(obj)
                    if(code === 200){
                        this.roleList = roleList
                    }
                }
            }
        }
    </script>
    

5. Start the project

⭐ Start the project in the development environment

1. Configure package.json


  "scripts": {
    
    
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "local": "vue-cli-service build --mode local", // 新加的
  },  

2. Open the command line

  yarn local # 运行项目

Summarize

I have been procrastinating for three days, and today I finally sorted this out. I admit that I am lazy. I have been relatively busy at work these days. Maybe it will be better to come back during the National Day! Today, through axiosthe simple encapsulation of requests, I have a new understanding of modularity. What I want to say most is that sometimes it is really happy to put down the effort to accomplish something, whether it is big or small. But the completion process is really a joy from the bottom of my heart. Some people say that they must do big things to define a person's success, but aren't the little things we do every time the cornerstone of our success?

Guess you like

Origin blog.csdn.net/weixin_44013288/article/details/120565470