【问题标题】:How to setup the url of the backend site on react build for production如何在用于生产的反应构建中设置后端站点的 url
【发布时间】:2023-02-02 00:52:18
【问题描述】:

当站点以开发方式“npm start”运行时,使用的后端 url 来自 package.json 的代理。

当我选择生产方式“npm build”时,不使用 package.json 中的后端 url,因为该代理仅用于开发。

我需要一些帮助来了解如何配置后端 url,我在开发和生产中使用相同的 url。

在配置文件.package.json 中:

{
  "name": "mysite_frontend_v1",
  "version": "0.1.0",
  "private": true,
  "proxy": "https://api.mysite.com",
...
} 

然后创建了一个文件 .env :

REACT_APP_API_URI = 'https://api.mysite.com'

api.js 文件:

function request(path, { data = null, token = null, method = 'GET' }) {
  return fetch(path, {
    method,
    headers: {
      Authorization: token ? `Token ${token}` : '',
      'Content-Type': 'application/json',
    },
    body: method !== 'GET' && method !== 'DELETE' ? JSON.stringify(data) : null,
  })
    .then((response) => {
      // If it is success
      if (response.ok) {
        if (method === 'DELETE') {
          // If delete, nothing return
          return true;
        }
        return response.json();
      }

      // Otherwise, if there are errors
      return response
        .json()
        .then((json) => {
          // Handle JSON error, response by the server
          if (response.status === 400) {
            const errors = Object.keys(json).map((k) => `${json[k].join(' ')}`);
            throw new Error(errors.join(' '));
          }
          throw new Error(JSON.stringify(json));
        })
        .catch((e) => {
          throw new Error(e);
        });
    })
    .catch((e) => {
      // Handle all errors
      toast(e.message, { type: 'error' });
    });
}

export function signIn(username, password) {
  return request('/auth/token/login/', {
    data: { username, password },
    method: 'POST',
  });
}

export function register(username, password) {
  return request('/auth/users/', {
    data: { username, password },
    method: 'POST',
  });
}

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    我不知道这是否是最好的解决方案,如果有人找到更好的解决方案,我会很高兴。

    所以我开始删除代理:

    {
      "name": "mysite_frontend_v1",
      "version": "0.1.0",
      "private": true,
    
    } 
    
    

    然后保留 .env 文件:

    REACT_APP_API_URI = 'https://api.mysite.com'
    
    

    在 api.js 文件中添加了一个常量:

    const base_url = process.env.REACT_APP_API_URI
    
    function request(path, { data = null, token = null, method = 'GET' }) {
      return fetch( base_url + path, {
        method,
        headers: {
          Authorization: token ? `Token ${token}` : '',
          'Content-Type': 'application/json',
        },
        body: method !== 'GET' && method !== 'DELETE' ? JSON.stringify(data) : null,
      })
        .then((response) => {
          // If it is success
          if (response.ok) {
            if (method === 'DELETE') {
              // If delete, nothing return
              return true;
            }
            return response.json();
          }
    
          // Otherwise, if there are errors
          return response
            .json()
            .then((json) => {
              // Handle JSON error, response by the server
              if (response.status === 400) {
                const errors = Object.keys(json).map((k) => `${json[k].join(' ')}`);
                throw new Error(errors.join(' '));
              }
              throw new Error(JSON.stringify(json));
            })
            .catch((e) => {
              throw new Error(e);
            });
        })
        .catch((e) => {
          // Handle all errors
          toast(e.message, { type: 'error' });
        });
    }
    
    export function signIn(username, password) {
      return request('/auth/token/login/', {
        data: { username, password },
        method: 'POST',
      });
    }
    
    ...
    

    但是我开始遇到 CORS 问题,所以需要在后端进行更改,那是在 django 中。

    所以我按照这个答案进行了 CORS 配置。

    How can I enable CORS on Django REST Framework

    之后,一切正常,无论是生产还是开发,在这种情况下不再使用代理。

    【讨论】:

      【解决方案2】:

      代理功能不适用于生产。 因此,您必须在 .env 文件中设置主机 URL

      【讨论】:

      • 感谢您的回答,您能帮我解决这个问题吗?在这个问题中,我展示了我的 .env 文件如何,但是我如何在 React 应用程序中调用它?
      • 像这样调用 .env 变量:process.env.REACT_APP_API_URI
      猜你喜欢
      • 2019-02-14
      • 1970-01-01
      • 2021-09-24
      • 2018-04-12
      • 2023-01-11
      • 1970-01-01
      • 2014-03-27
      • 2020-10-16
      • 2015-12-14
      相关资源
      最近更新 更多