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

查看:25
本文介绍了生产中的 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 的虚拟主机上,但我真的不知道如何配置我的前端以使用像 http://api.domain-name.com 用于后端.我知道我可以在我的 fetchData 方法中写 api.domain-name.com,但我不想硬编码那个地址,因为我计划这个项目被其他人使用,所以,很明显,一些他们,甚至我,都不想让他们手动更改前端试图到达后端的那些代码行.我希望这可以通过配置文件以某种方式完成,例如,我可以在其中编写类似 HOST: 'api.domain-name.com' 的内容,然后在项目中导入该文件并使用 HOST 常量.有人可以帮我提供建议吗?

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?

推荐答案

你应该使用 ENV 变量来做到这一点

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天全站免登陆