首页 > 解决方案 > 使用 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我仍然拥有localhosturl。

如何构建它以便在本地开发它使用 localhost 但部署它使用不同的 url?

一旦我在 Azure 中,我将拥有一个前端和多个后端,需要根据谁登录来指向它们。

如何配置 API 管理层以根据谁登录(使用 AD 进行身份验证)将调用路由到正确的后端?

由于我使用 APIM 进行路由,应该baseURL是什么?

标签: reactjsazurerestaxios

解决方案


在配置文件中管理这些变量并根据环境加载。

本地值,您可以直接在配置文件中硬编码局部变量

生产价值 - 保留占位符并从构建管道中设置它们或 - 也对它们进行硬编码

例如:

配置.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;

推荐阅读