【问题标题】:Change axios BaseURL dynamically based on select html element根据select html元素动态更改axios BaseURL
【发布时间】:2021-10-30 06:33:17
【问题描述】:

我有一个 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 中。

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

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 几乎是不可能的。有人可以告诉我路吗? :)

【问题讨论】:

    标签: javascript vuejs2 axios


    【解决方案1】:

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

    axios_instance.defaults.baseURL = "selected url";
    

    【讨论】:

      猜你喜欢
      • 2019-10-22
      • 1970-01-01
      • 2020-08-17
      • 2020-03-09
      • 1970-01-01
      • 2019-09-04
      • 1970-01-01
      • 1970-01-01
      • 2018-10-25
      相关资源
      最近更新 更多