javascript - 根据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 几乎是不可能的。有人可以告诉我路吗?:)
解决方案
您可以更改默认基本网址https://axios-http.com/docs/config_defaults
axios_instance.defaults.baseURL = "selected url";
推荐阅读
- java - 如何在回收站视图中只选择一个开关?
- elasticsearch - 无法使用 Elasticsearch apm 代理选项启动 Weblogic
- php - 为什么标头功能无法正常工作?
- android - 为什么我不能通过电话调试我的 Android 项目?
- python - Jinja2迭代包含字典列表模板错误的字典
- java - HttpClient 超时,但服务器可用并且工作正常
- c# - 如何在集群表上从 Bigquery 查询?
- reactjs - 有没有更好的方法来编写这个 React 打字动画?
- tensorflow - 不支持 tflite 转换器错误操作
- linux - haproxy 将 URL 的查询重定向到另一个 URL