A method for unified management of multiple back-end URLs in a vue project

A method for unified management of multiple back-end URLs in a vue project

If there are multiple backend services with different URLs, you can create a configuration file to manage these URLs uniformly. Here is a simple example:

  1. Create a file called config.jsor apiConfig.js(or something similar) as a configuration file.

  2. Define your backend URL in a configuration file, for example:

// config.js

const apiUrl1 = 'http://backend1.com';
const apiUrl2 = 'http://backend2.com';

export {
    
     apiUrl1, apiUrl2 };
  1. Import the configuration file in code, and use the URL from it as needed. You can choose to use it in Vue instance, Axios plugin or component according to your own situation.
  • Use in Vue instance:
import {
    
     apiUrl1 } from './config';

const app = createApp(App);
app.config.globalProperties.$apiUrl1 = apiUrl1;

app.mount('#app');
  • Use in Axios plugin:
import axios from 'axios';
import {
    
     apiUrl1 } from './config';

export default {
    
    
  install(app) {
    
    
    axios.defaults.baseURL = apiUrl1;
    app.config.globalProperties.$axios = axios;
  },
};
  • In the component use:
import {
    
     apiUrl1 } from './config';

export default {
    
    
  methods: {
    
    
    fetchData() {
    
    
      this.$axios.get(`${
      
      apiUrl1}/your-api-endpoint`)
        .then(response => {
    
    
          // 处理响应
        })
        .catch(error => {
    
    
          // 处理错误
        });
    },
  },
};

Through the above method, you can easily manage multiple backend URLs in a unified manner, and use them in different parts as needed. URLs can be changed by modifying configuration files without searching and replacing URL strings throughout the code.

Guess you like

Origin blog.csdn.net/qq_51447496/article/details/131396569