尝试从已部署的create-react-app中的公用文件夹中获取json文件时出现404错误 [英] 404 Error when trying to fetch json file from public folder in deployed create-react-app
问题描述
我的反应项目公用文件夹中有一个json文件,像这样
public|| ___ Data|test.json
在我的.tsx文件中,我引用的是这样的文件
fetch(`$ {process.env.PUBLIC_URL}/Data/test.json`,{标头:{'Content-Type':'application/json','接受':'应用程序/json'}}).then(响应=>响应)
这在开发中以及在本地构建和服务应用程序(npm run build)时都可以正常工作.但是,当我尝试部署到我的Azure Web应用程序服务时,该网站对该文件引发404错误.
我还可以在Kudu调试控制台中看到该文件,因此我知道该文件将随项目一起部署.
将 process.env.PUBLIC_URL
打印到控制台会产生一个空字符串.我是否需要使用环境变量将此值设置为某些值?我的应用程序服务配置中还有其他东西吗?
我看过其他类似的问题,即
npm运行构建,并部署构建文件夹.
进行测试.
重要
方法1
您可以在门户网站的应用程序设置
中设置 PUBLIC_URL
.
测试步骤:
-
在门户网站上配置.
-
打开scm网站,单击
环境
. -
打开ssh,运行命令.
方法2
尝试使用 process.env.WEBSITE_HOSTNAME
代替 process.env.PUBLIC_URL
.
I have a json file in my react project public folder like this
public
|
|___Data
| test.json
In my .tsx file I’m referencing the file like this
fetch(`${process.env.PUBLIC_URL}/Data/test.json`,
{
headers : {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
.then(response => response)
This works fine in development and when building and serving the app locally (npm run build). But when I try deploy to my Azure web app app service, the site throws a 404 error for that file.
I can also see the file in the Kudu debug console so I know it's getting deployed with the project.
Printing process.env.PUBLIC_URL
to console yields an empty string. Do I need to set this value to something using environment variables? Is there something else that I’m missing with my app service configuration?
I've looked at other similar questions, namely this one and the solution did not work for me either.
NEWEST
The React client side project essentially downloads a piece of code to run on the client browser, and will not be related to azure application settings. So its process.env cannot read any azure environment variables.
The latest updated answer can be your alternative. After a lot of testing, it is found that in the react project, the process.env in the .tsx file is different from the global one.
import * as React from 'react';
const {env} = process;
...
public getJsonDataStr = () => {
const urlBy: string = this.props.urlBy!;
const url = this.state.url + urlBy + env.REACT_APP_PUBLIC_URL;
this.setState({ url });
};
For more details, you can download my sample code.
Create
.env
file in project.npm run build, and deploy build folder.
Test it.
PRIVIOUS
Method 1
You can set PUBLIC_URL
in Application settings
on portal.
Test Step:
configure on portal.
Open scm site, click
Environment
.open ssh, run command.
Method 2
Try to use process.env.WEBSITE_HOSTNAME
instead of process.env.PUBLIC_URL
.
这篇关于尝试从已部署的create-react-app中的公用文件夹中获取json文件时出现404错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!