axios configures multiple interface requests (3) - vue project axios configures multiple IP addresses and configures multiple interface requests

axios configures multiple interface requests (3) - vue project axios configures multiple IP addresses and configures multiple interface requests

Configure multiple IP addresses in the Vue project and configure multiple interface requests for each IP address. You can configure it as follows:

1. Create a configuration file, for example apiConfig.js, to store the configuration information requested by the IP address and interface.

// apiConfig.js

export const API_BASE_URL_1 = 'http://ip1.example.com';
export const API_BASE_URL_2 = 'http://ip2.example.com';

export const API_ENDPOINTS = {
    
    
  endpoint1: '/api/endpoint1',
  endpoint2: '/api/endpoint2',
  // 添加其他接口请求的配置...
};

2. Create an API file, such as api.js, to store the definition and configuration of interface requests.

// api.js

import axios from 'axios';
import {
    
     API_BASE_URL_1, API_BASE_URL_2, API_ENDPOINTS } from '@/apiConfig';

// 创建一个 Axios 实例
const instance1 = axios.create({
    
    
  baseURL: API_BASE_URL_1,
});

const instance2 = axios.create({
    
    
  baseURL: API_BASE_URL_2,
});

// 定义接口请求函数
export function requestEndpoint1() {
    
    
  return instance1.get(API_ENDPOINTS.endpoint1);
}

export function requestEndpoint2() {
    
    
  return instance2.get(API_ENDPOINTS.endpoint2);
}

// 添加其他接口请求函数...

3. In the component that needs to initiate a request, import and call the corresponding interface request function.

// YourComponent.vue

import {
    
     requestEndpoint1, requestEndpoint2 } from '@/api';

export default {
    
    
  methods: {
    
    
    async fetchData() {
    
    
      try {
    
    
        const response1 = await requestEndpoint1();
        console.log(response1.data);

        const response2 = await requestEndpoint2();
        console.log(response2.data);

        // 发起其他请求...
      } catch (error) {
    
    
        console.error(error);
      }
    },
  },
};

In the above example, by importing the IP address and interface request configuration information, you can use these configurations to build the complete URL of the request wherever you need to make the request. Through the Axios instance created instance1with and instance2, you can make requests for different IP addresses.

Through the form of requestEndpoint1()and requestEndpoint2(), you can call the corresponding interface request function and initiate a request to the corresponding IP address and interface endpoint.

In this way, you can configure multiple IP addresses in the Vue project and configure multiple interface requests for each IP address. Based on actual needs, you can add more IP address and interface request configurations in the configuration file, and use them in the component to make requests as needed.

Guess you like

Origin blog.csdn.net/weixin_44867717/article/details/132696027