reactjs - 使用 Azure API 管理运行 React 时如何配置 REST URL?
问题描述
我有一个 reactjs 前端,它通过 rest 调用从 spring boot 后端获取数据。
在本地运行此代码如下所示:
axios.defaults.baseURL = 'http://localhost:8080/api';
axios.get('/devices').then((resp) => {
this.setState({devices: resp.data});
}).catch(() => {
console.log('Failed to retrieve device details');
});
当我构建要部署的代码时,npm run build
我仍然拥有localhost
url。
如何构建它以便在本地开发它使用 localhost 但部署它使用不同的 url?
一旦我在 Azure 中,我将拥有一个前端和多个后端,需要根据谁登录来指向它们。
如何配置 API 管理层以根据谁登录(使用 AD 进行身份验证)将调用路由到正确的后端?
由于我使用 APIM 进行路由,应该baseURL
是什么?
解决方案
在配置文件中管理这些变量并根据环境加载。
本地值,您可以直接在配置文件中硬编码局部变量
生产价值 - 保留占位符并从构建管道中设置它们或 - 也对它们进行硬编码
例如:
配置.js
const serverVars = {
authUrl: '#{authUrl}#',
apiUrl: '#{apiUrl}#',
};
const localVars = {
authUrl: 'local_auth_url',
apiUrl: 'local_api_url',
};
export function getConfiguration() {
if (process.env.NODE_ENV === 'production') {
return serverVars;
}
return localVars;
}
当你调用 apiUrl
import axios from 'axios';
import { getConfiguration } from 'config';
axios.defaults.baseURL = getConfiguration().apiUrl;
推荐阅读
- tabs - 如何使 VS Code 编辑器选项卡在左侧关闭?
- java - 为什么持久化后休眠复合对象不完整?
- java - 设置Activity中所有元素的文字颜色
- javascript - 根据我自己的位置居中标记时出错
- php - 如何更改upload_max_filesize
- python - python:测试数组并打印名称
- keycloak - Keycloak 状态参数无效
- amazon-web-services - 恢复通过 zappa 部署的代码
- angular - 仅在 --prod build 中出现 Okta Angular 错误
- selenium-webdriver - 在移动浏览器中模拟实时性能测试的最佳方法是什么?