简体   繁体   中英

How to get the path to a file outside the root folder in React application

This is simplified folder structure in my React application created with the create-react-app. For the back-end I'm using the Express framework.

└── ReactApp/
    ├── client/
    |  ├── node_modules/
    |  ├── public/
    |  └── src/
    |      └── components/
    |         └── component.js
    └── server/
       ├── index.js
       └── Uploads/
           └── file.txt

Inside component.js file I want to define the path to the file.txt file located to the server/Uploads folder.

 handleClick() {
        const pathToFile = '../../server/Uploads/file.txt;
        this.setState({ input: pathToFile})
  }

The issue is that this defined path cannot locate the txt file inside the Uploads folder.

Try:

handleClick() {
   const pathToFile = '../../../server/Uploads/file.txt';
   this.setState({ input: pathToFile})
}

The solution is to configure ExpressJS to serve static files inside the Uploads folder.

index.js

app.use(express.static('Uploads'));

and then change the path inside the component.js file.

handleClick() {
    const pathToFile = 'file.txt';
    this.setState({ input: pathToFile})
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM