簡體   English   中英

如何在 React 應用程序中獲取根文件夾之外的文件的路徑

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

這是我使用 create-react-app 創建的 React 應用程序中的簡化文件夾結構。 對於后端,我使用的是 Express 框架。

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

component.js文件中,我想定義位於server/Uploads文件夾的file.txt文件的路徑。

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

問題是這個定義的路徑無法在 Uploads 文件夾中找到 txt 文件。

嘗試:

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

解決方案是將 ExpressJS 配置為在 Uploads 文件夾中提供 static 文件。

index.js

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

然后更改component.js文件中的路徑。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM