【问题标题】:react and express: get image from public folder反应和表达:从公共文件夹中获取图像
【发布时间】:2021-07-07 18:13:12
【问题描述】:

我通过 1 个 nodejs 后端为 2 个不同的 react 应用程序提供服务。 Nodejs 代码(简化):

const api = require('./api/routes');
app.use('/api', api);

const admin = require('./admin/routes');
app.use('/api/admin', admin);

app.use('/admin', express.static(path.join(__dirname, '/react/admin-client/build/')));
app.get('/admin/*', (req, res) => {
  res.sendFile(path.join(__dirname, '/react/admin-client/build/index.html'))
});

app.use(express.static(path.join(__dirname, '/react/client/build/')));
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, '/react/client/build/index.html'))
});

当我导航到 localhost:5000/admin(管理客户端应用程序)时,我看到了管理客户端并且一切正常。但是当我导航到 localhost:5000(客户端应用程序)时,我看到了该应用程序,但未找到公用文件夹中的资产。

当管理客户端中的 console.logging process.env.PUBLIC_URL 时,我得到/admin。当我在客户端中 console.log 相同的事情时,我得到一个空白响应。

我正在使用 apache vhost 代理从 localhost(:80) 到 localhost:5000 的请求。

<VirtualHost *:80>
    ServerName localhost
    ServerAlias localhost
    ProxyPass "/" http://localhost:5000/
</VirtualHost>

访问 http://localhost/admin/logo.png 时,我得到了公共文件夹中的 admin-client react 应用程序的徽标。

当访问 http://localhost/logo.png 时,我没有得到位于 public 文件夹中的客户端 react 应用程序的徽标,相反,它被视为一个页面(在 url 后附加一个“/”)。

【问题讨论】:

    标签: node.js reactjs


    【解决方案1】:

    我遇到了同样的问题。我的服务器位于 /appDirectory/config/expressSetup.ts 之类的目录中

     public app: express.Application;
    
    constructor() {
        this.app = express();
        this.appClient = express();
        this.config();
        this.routes();
        if (!IS_DEV_MODE) {
            this.app.use(express.static(path.join(__dirname, '../../../client/build')));
            this.app.use('*', (req, res, next) => {
                res.sendFile(path.join(__dirname, '../../../client/build', 'index.html'));
            });
        }
        this.errorHandler();
    }
    

    我的客户位于 /appDirectory/client/build。确保您的文件夹包含放置在构建文件夹中的文件图标。

    【讨论】:

      猜你喜欢
      • 2020-02-06
      • 2022-07-28
      • 1970-01-01
      • 2021-12-02
      • 2022-08-14
      • 2018-04-22
      • 2021-12-04
      • 1970-01-01
      • 2019-11-28
      相关资源
      最近更新 更多