当在控制台中只看到空字符串时,如何选择服务器的正确URL进行GET请求?

huangapple go评论70阅读模式
英文:

How the correct url of my server is picked when making GET request, when in console.log I see only empty string?

问题

我在服务器和浏览器中都使用create-react-app、webpack4.3和axios,已经在控制台中记录了process.env.PUBLIC_URL,但我只看到了""。那么,在控制台中只看到空字符串时,如何在进行GET请求时选择我的服务器的正确URL?

我在开发工具的网络选项卡中看到了正确的URL。

英文:

Using create-react-app, webpack4.3, axios

I have console logged process.env.PUBLIC_URL in both server and browser, but all I see is "". Then, how the correct url of my server is picked when making GET request, when in console.log I see only empty string?

I see the correct url in Network tabs of developer tools.

答案1

得分: 1

在create-react-app关于环境变量的文档中,他们提到了这个两次

>注意:您必须创建以REACT_APP_开头的自定义环境变量。除了NODE_ENV之外的任何其他变量都将被忽略,以避免意外地在具有相同名称的机器上公开私钥

所以最奇怪的部分是当记录process.env.PUBLIC_URL时,它是""而不是undefined


但是当process.env.PUBLIC_URL为空字符串时,您的请求按预期工作,所以我唯一能想到的是您在package.json文件中设置了代理与基本URL字符串。

"proxy": "http://localhost:4000",

>要告诉开发服务器在开发中代理任何未知请求到您的API服务器,请在您的package.json中添加一个代理字段<br>
>这样,当您在开发中获取('/api/todos')时,开发服务器将识别它不是静态资源,并将您的请求代理到http://localhost:4000/api/todos作为备用。

请随意点踩这个,我也认为它应该是一条评论,但你知道,它不行。

英文:

In create-react-app docs about environment variables they have mentioned this two times

>Note: You must create custom environment variables beginning with REACT_APP_. Any other variables except NODE_ENV will be ignored to avoid accidentally exposing a private key on the machine that could have the same name

so the weirdest part is when log process.env.PUBLIC_URL and its is &quot;&quot; and not undefined.


but your requests work as expected while rocess.env.PUBLIC_URL is an empty string so the only thing I can think of is that you had set a proxy with the base URL string in your package.json file.<br>

&quot;proxy&quot;: &quot;http://localhost:4000&quot;,

>To tell the development server to proxy any unknown requests to your API server in development, add a proxy field to your package.json <br>
>This way, when you fetch('/api/todos') in development, the development server will recognize that it’s not a static asset, and will proxy your request to http://localhost:4000/api/todos as a fallback.

feel free to downvote this, I also think it should be a comment, but you know, it can't.

huangapple
  • 本文由 发表于 2023年6月15日 19:30:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/76482011.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定