首页 > 解决方案 > 无法使用 Express / Node 提供静态 HTML 文件

问题描述

我正在使用 Express 和 Node,然后用它构建一个 React 应用程序,它是单页的,除了一个静态 HTML 文件。

我有这个在本地工作,所以当我去的时候localhost:3000/static-file.html,我可以看到文件。但这在生产中不起作用。

我什至无法点击任何测试console.log语句,所以我知道在请求static-file.html. app.js请参阅我文件的以下部分:

if (process.env.NODE_ENV === "production") {
  app.get('/static-file.html', function (req, res) {
    console.log('test1');
  });
  app.get('static-file.html', function (req, res) {
    console.log('test2');
  });
  app.get('static-file', function (req, res) {
    console.log('test3');
  });
  app.get('/static-file', function (req, res) {
    console.log('test4');
  });

  app.use(express.static("client/build"));
}

当我转到 production-site.com/static-file.html 时 - 我仍然看到索引,与 localhost 不同。

有人可以帮我吗?非常感谢。

标签: node.jsreactjsexpress

解决方案


Try something like this:
    const express = require('express');
    const app = express();
    const path = require('path');

    // the __dirname is the current directory from where the script is running
    app.use(express.static(__dirname));
    app.use(express.static(path.join(__dirname, 'build')));
    app.get('*', (req, res) => {
      res.sendFile(path.join(__dirname + '/build/index.html'))
    })

    /* Here build is the production build directory and index.html is the main html page to show */

推荐阅读