Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.8k views
in Technique[技术] by (71.8m points)

reactjs - 404 Error when trying to fetch json file from public folder in deployed create-react-app

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

  1. Create .env file in project.

    enter image description here

  2. npm run build, and deploy build folder.

    enter image description here

  3. Test it.

enter image description here

PRIVIOUS

Method 1

You can set PUBLIC_URL in Application settings on portal.

Test Step:

  1. configure on portal.

    enter image description here

  2. Open scm site, click Environment.

    enter image description here

  3. open ssh, run command.

    enter image description here

Method 2

Try to use process.env.WEBSITE_HOSTNAME instead of process.env.PUBLIC_URL.

enter image description here

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...