[VUE] 6. Introduce axios into the VUE project

1. Getting to know axios for the first time

Axios is a promise-based network request library that works in node.js and browsers. It is isomorphic (that is, the same set of code can run in browsers and node.js). On the server side it uses the native node.js http module, and on the client side (browser side) it uses XMLHttpRequest.

  • main feature:

Create XMLHttpRequests from browsers
Create http requests from node.js
Support Promise API
to intercept requests and responses
Transform request and response data
Cancel requests
Automatically convert JSON data
Client side supports defense against XSRF

2. Install axios

  • 1. Install axios
npm install axios
  • 2. Mount axios
    In the main.js file, add the following content:
import axios from 'axios'
Vue.prototype.$http= axios

We can initiate a request through this.$http

3. Configure network proxy

const {
    
    defineConfig} = require('@vue/cli-service')

module.exports = defineConfig({
    
    
    transpileDependencies: true,
    devServer: {
    
    
        // 指定使用的ip地址,默认为localhost,如果使用'0.0.0.0'则可以被外部访问
        host: '0.0.0.0',
        // 指定服务监听的端口号
        port: 9527,
        // 代理
        proxy: {
    
    
            [process.env.VUE_APP_BASE_API]: {
    
    
                target: 'http://localhost:8080',
                changeOrigin: true,
                pathRewrite: {
    
    
                    ['^' + process.env.VUE_APP_BASE_API]: ''
                }
            }
        }
    }
})

Among them, process.env.VUE_APP_BASE_API is the request path we configured in the multi-environment configuration file, for example, the .env.development file:

# Asurplus管理系统/开发环境
VUE_APP_BASE_API = '/dev-api'

Then the request path we send is:

http://localhost:9527/dev-api/xxx

4. Use axios

httpTest() {
    
    
  this.$http.get(process.env.VUE_APP_BASE_API + '/test').then(res => {
    
    
    console.log(res)
  })
}

The response I got:

{
    
    
    "data":{
    
    
        "msg":"操作成功",
        "code":200,
        "data":"this is data"
    },
    "status":200,
    "statusText":"OK",
    "headers":{
    
    
        "connection":"close",
        "content-encoding":"gzip",
        "content-type":"application/json;charset=UTF-8",
        "date":"Mon, 03 Apr 2023 06:47:10 GMT",
        "transfer-encoding":"chunked",
        "vary":"Accept-Encoding",
        "x-powered-by":"Express"
    },
    "config":{
    
    
        "transitional":{
    
    
            "silentJSONParsing":true,
            "forcedJSONParsing":true,
            "clarifyTimeoutError":false
        },
        "adapter":[
            "xhr",
            "http"
        ],
        "transformRequest":[
            null
        ],
        "transformResponse":[
            null
        ],
        "timeout":0,
        "xsrfCookieName":"XSRF-TOKEN",
        "xsrfHeaderName":"X-XSRF-TOKEN",
        "maxContentLength":-1,
        "maxBodyLength":-1,
        "env":{
    
    

        },
        "headers":{
    
    
            "Accept":"application/json, text/plain, */*"
        },
        "method":"get",
        "url":"/dev-api/test"
    },
    "request":{
    
    

    }
}

It can be seen that some network response status and information are also obtained together, but we need to judge whether the httpStatus is 200 every time in order to perform normal business logic processing, which is very cumbersome

5. Configure request interceptor and response interceptor

import axios from 'axios'
import {
    
    Message} from 'element-ui'

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// 创建axios实例
const service = axios.create({
    
    
    // axios中请求配置有baseURL选项,表示请求URL公共部分
    baseURL: process.env.VUE_APP_BASE_API,
    // 超时
    timeout: 10000
})
// request拦截器
service.interceptors.request.use(config => {
    
    
    // get请求映射params参数
    if (config.method === 'get' && config.params) {
    
    
        let url = config.url + '?';
        for (const propName of Object.keys(config.params)) {
    
    
            const value = config.params[propName];
            const part = encodeURIComponent(propName) + "=";
            if (value !== null && typeof (value) !== "undefined") {
    
    
                if (typeof value === 'object') {
    
    
                    for (const key of Object.keys(value)) {
    
    
                        let params = propName + '[' + key + ']';
                        const subPart = encodeURIComponent(params) + "=";
                        url += subPart + encodeURIComponent(value[key]) + "&";
                    }
                } else {
    
    
                    url += part + encodeURIComponent(value) + "&";
                }
            }
        }
        url = url.slice(0, -1);
        config.params = {
    
    };
        config.url = url;
    }
    return config
}, error => {
    
    
    Promise.reject(error)
})

// response拦截器
service.interceptors.response.use(res => {
    
    
        // 未设置状态码则默认成功状态
        const code = res.data.code || 200;
        // 获取错误信息
        const msg = res.data.msg
        if (200 !== code) {
    
    
            Message({
    
    
                message: msg,
                type: 'error'
            })
            return Promise.reject(new Error(msg))
        }
        // 返回响应信息
        else {
    
    
            return res.data
        }
    },
    error => {
    
    
        let {
    
    message} = error;
        if (message === "Network Error") {
    
    
            message = "后端接口连接异常";
        } else if (message.includes("timeout")) {
    
    
            message = "系统接口请求超时";
        } else if (message.includes("Request failed with status code")) {
    
    
            message = "系统接口" + message.substr(message.length - 3) + "异常";
        }
        Message({
    
    
            message: message,
            type: 'error',
            duration: 5 * 1000
        })
        return Promise.reject(error)
    }
)

export default service
  • 1. Request interceptor

1. The default request header content: Content-Type=application/json;charset=utf-8, if you need to pass token and other authentication information, you can add it to the request interceptor 2. Configure the default request timeout time: 10s 3.
Get
request If the params parameter is passed, the parameters will be spliced ​​on the request address according to the method of ?key=value&key1=value1

  • 2. Response interceptor

1. By default, the returned code = 200 is a successful response, and the data object in the response information is returned.
2. The error response at the request business level will directly prompt the msg information in the business response object.
3. The error response at the request network level will be prompted according to the error type Response prompt message

6. Package request

  • 1、test.js
import request from '@/utils/request'

export function test(data) {
    
    
    return request({
    
    
        url: '/test',
        method: 'post',
        data: data
    })
}
  • 2. Initiate a request

Introduce the request interceptor and response interceptor we just configured, data is the parameter we need to pass, and use it in the component:

import {
    
    test} from "@/api/test";
methods: {
    
    
  httpTest() {
    
    
    test(this.data).then(res => {
    
    
      console.log(res)
    })
  }
}

The response I got:

{
    
    
    "msg":"操作成功",
    "code":200,
    "data":"this is data"
}

If you find deficiencies in reading, please leave a message! ! !

Guess you like

Origin blog.csdn.net/qq_40065776/article/details/129928761