首页 > 解决方案 > 根据select html元素动态更改axios BaseURL

问题描述

我有一个 vuejs 应用程序,可以与地理上不同的多个相同后端进行通信。每个端点都有一个唯一的 URL - 示例:

export const SERVICE_BASE_API_URLS =  [
    { name: 'Site A', endpoint: 'http://api.a.service.com/api/v1/' },
    { name: 'Site B: 'http://api.b.service.com/api/v1' },
}

我允许用户通过选择框选择他们想要与之交互的端点。我想设置选定的 URL 以用于 axios 的任何进一步的全局交互。我认为设置 Vue.Prototype.$current_endpoint 会起作用。

所以我有选择元素的 onchange 动作将它的端点值存储在 Vue.Prototype.$current_endpoint 中。

一旦auth-header.js由authentication.js导入,我必须设置一个由多个端点类使用的axios实例

import axios from 'axios';
import * as URLConstants from '../configs/urls';

export const axios_instance = axios.create({
  //baseURL: URLConstants.Service_BASE_API_URL, // this was earlier set in .env. But this would be statically set for the vue instance
  baseURL: Vue.prototype.current_api_endpoint
})

axios_instance.interceptors.request.use(
  function(config) {
    if (JSON.parse(localStorage.getItem('user')) && JSON.parse(localStorage.getItem('user')).access_token) {

      const token = JSON.parse(localStorage.getItem('user')).access_token
      config.headers["JWTAuthorization"] = 'Bearer ' + token;
    }
    return config;
  },
  function(error) {
    return Promise.reject(error);
  }
);

所以后来在interact-with-service.js中我有

import {
  axios_instance
} from './auth-header';
import APIMixin from './mixin';


class ExpenseService extends APIMixin {
  get(params) {
  ...
  ...
    return axios_instance
      .get("expense" + params)
      .then(this.handleResponse);
}

但是,我发现正确设置 axios 基本 URL 几乎是不可能的。有人可以告诉我路吗?:)

标签: javascriptvuejs2axios

解决方案


您可以更改默认基本网址https://axios-http.com/docs/config_defaults

axios_instance.defaults.baseURL = "selected url";

推荐阅读