Secondary encapsulation, decoupling, environment variables, and cross-domain of axios

1. The secondary encapsulation of axios
creates the utils file in the src folder and creates request.js in the utils folder.

// 1、引入axios
import axios from "axios";

// console.log( process.env )
// 2、创建axios对象
const instance = axios.create({
    
    
    //baseURL: process.env.NODE_ENV == 'production' ? process.env.VUE_APP_BASE_URL: "",
    baseURL:'http://localhost:3000',//路径      
    timeout: 5000,                  //请求时间
    // headers: { 'X-Custom-Header': 'foobar' } //请求头
});



///3、添加请求拦截器 ====> 前端给后端的参数 [还没到后端响应]
instance.interceptors.request.use(function (config) {
    
    
    // 在发送请求之前做些什么
    // 这里一般会做 登录的判断,如果用户是登录状态,会在headers中把用户的token传递给后端
    
    // if( xxx ) {
    
    
    //     instance.headers.token = xxx
    // }

    console.log(1)
    return config;
}, function (error) {
    
    
    // 对请求错误做些什么
    return Promise.reject(error);
});

///4、添加响应拦截器 ====> 后端给前端的数据  [后端返回给前端]
instance.interceptors.response.use(function 
    (response) {
    
    
    // 2xx 范围内的状态码都会触发该函数。
    // 对响应数据做点什么

    // 后端给前端数据的时候,会有code码
    console.log(2)

    return response;
}, function (error) {
    
    
    // 超出 2xx 范围的状态码都会触发该函数。
    // 对响应错误做点什么
    return Promise.reject(error);
});


// 5、最终返回的对象
export default instance;

2.axios decoupling
Create an api folder under the src file and create a course.js file under its folder

// 导入request.js

import request from '@/utils/request.js'

export function getSecondCategorys() {
    
     //默认get请求

    return request( {
    
    
        url: '/api/course/category/getSecondCategorys',
    })
};


export function courseMostNew( data ) {
    
    

    return request( {
    
    
        url:'/api/course/mostNew',
        method:'post',
        data
    })
};


export function getList() {
    
     
   
    return request( {
    
    
        url:'/list'
    })
}


Directly import defined methods on the page

<template>
  <div>
	<h1>首页</h1>
  </div>
</template>

<script>
//接口
import {
    
     getList } from "@/api/course";
export default {
    
    
  data() {
    
    
    return {
    
    };
  },
  created() {
    
    
// console.log(process.env.VUE_APP_BASE_URL)

    getList().then(res=>{
    
    
		console.log(res)
	})

      
 },
  
};
</script>

<style>
</style>

4. How should the front-end solve cross-domain issues? ? ?
Configure the proxy in the vue.config.js folder

const {
    
     defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
    
    
  transpileDependencies: true,

  // 代理跨域
  /*
    devServer.proxy在开发阶段生效(生产阶段不生效)
    
  
  */
 publicPath:'./',
 transpileDependencies: true,
  devServer: {
    
    
    proxy: 'http://localhost:3000'
  }
})

5. The environment variable
devServer.proxy only takes effect in the development stage and not in the production stage. So what should we do? ? ?
Create two files at the same level as src, named: .env.development (development environment), .env.production (production environment)
Note: The attribute name in the .env file must start with VUE_APP_XXX
l For example,
Insert image description here
modify the baseURL in request.js Path:
process.env.NODE_ENV == 'production' ? process.env.VUE_APP_BASE_URL: "",

Guess you like

Origin blog.csdn.net/m0_45218136/article/details/127749974