[英]Not using 'localhost' in HOST for development with create-react-app
My problem is quite simple: I would like to avoid using localhost
at the end of my HOST
env variable with create-react-app. 我的问题很简单:我想避免在带有create-react-app的
HOST
env变量的末尾使用localhost
。 However it seems that if the URL doesn't end with .localhost
, the script will try to resolve the URL against a DNS server. 但是,如果URL并非以
.localhost
,则脚本将尝试针对DNS服务器解析URL。
I would like to avoid that and just use the same URL domain as my backend server is using, to avoid CORS problems (and I wish not to configure my backend to allow CORS because that's not how the production infrastructure is). 我想避免这种情况,只使用与后端服务器使用的URL域相同的URL域,以避免发生CORS问题(并且我不希望将后端配置为允许CORS,因为这不是生产基础结构的方式)。
Thanks :) 谢谢 :)
The true problem you're facing here is CORS. 您在这里面临的真正问题是CORS。 The standard solution for this is actually to just proxy your request, so that they're hitting from the same origin.
实际上,标准解决方案是仅代理您的请求,以使它们来自同一来源。 Webpack has a clean way to do this.
Webpack有一个干净的方法可以做到这一点。 See this blog by facebook: https://facebook.github.io/create-react-app/docs/proxying-api-requests-in-development
通过Facebook查看此博客: https : //facebook.github.io/create-react-app/docs/proxying-api-requests-in-development
This has gotten incredibly easy to do now. 现在,这已经变得非常容易。 All you need to do is add a
proxy
field to your package.json
. 您需要做的就是将一个
proxy
字段添加到package.json
。 For example - 例如 -
"proxy": "http://localhost:4000",
If you want to use some custom domain locally, without resolving it agains a DNS server, you can add that domain to your hosts
file. 如果您想在本地使用某些自定义域,而无需再次解析DNS服务器,则可以将该域添加到
hosts
文件中。
Location of hosts
file on Windows: Windows上的
hosts
文件位置:
C:\Windows\System32\drivers\etc\hosts
Location of hosts
file on Mac: 在Mac上的
hosts
文件位置:
/etc/hosts
You can modify the hosts
file by adding the following line to it: 您可以通过添加以下行来修改
hosts
文件:
127.0.0.1 yourcustomdomain.com
This will bind yourcustomdomain.com
to your local IP. 这会将
yourcustomdomain.com
绑定到您的本地IP。 Now you can use yourcustomdomain.com
in your create-react-app
. 现在,您可以在
create-react-app
使用yourcustomdomain.com
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.