生产中的ReactJS API主机 [英] ReactJS API host in production

查看:54
本文介绍了生产中的ReactJS API主机的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

几个月前,我开始在业余时间创建一个开源项目,因此我已经用ReactJS编写了前端,并通过webpack devServer通过以下方式连接到后端API:

I started to create an open source project several months ago, in my spare time, so I have frontend written in ReactJS and I connect to backend API trough webpack devServer like this:

proxy: {
  '/api/**': {
    target: 'http://localhost:3001/project/backend',
    changeOrigin: true,
    pathRewrite: {
      '^/api': ''
    }
  }
}

我可以使用如下API来获取数据:

and I can fetch my data using API like this:

fetchData () {
  window.fetch('/api/')
    .then(res => res.json())
    ...
}

现在,我正尝试将我的项目部署在具有真实域名而不是localhost:3001的虚拟主机上,并且我真的不知道如何配置前端以使用类似

Now I'm trying to deploy my project on a web hosting with real domain name instead of localhost:3001 and I really can't figure out how to configure my frontend to use an addres like http://api.domain-name.com for backend. I know that I can just write api.domain-name.com in my fetchData method, but I don't want to to hardcode that address, because I am planning this project to be used by other people, so, obviously, some of them, and even I, don't want want to put them in situation to change manually those lines of code where frontend is trying to reach backend. I expect that this can be done somehow with a configuration file, for example, where I can write something like HOST: 'api.domain-name.com' and after that to import that file in project and to use the HOST constant. Can someone help me with an advise?

推荐答案

您应使用> c0> 变量来执行此操作

You should use ENV variables to do this

REACT_APP_API_HOST = example.com纱线运行构建

REACT_APP_API_HOST=example.com yarn run build

在webpack中传递与环境相关的变量

这篇关于生产中的ReactJS API主机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆