简体   繁体   English

无法使用Express / Node服务静态HTML文件

[英]Can't Serve Static HTML File with Express / Node

I am using Express with Node and then building a React app with this which is single page, except one static HTML file. 我正在将Express与Node一起使用,然后用一个页面(一个静态HTML文件除外)构建一个React应用程序。

I have this working locally, so when I go to localhost:3000/static-file.html , I can see the file. 我在本地工作,因此当我转到localhost:3000/static-file.html ,可以看到该文件。 But this doesn't work in production. 但这在生产中不起作用。

I can't even hit any of the test console.log statements, so I know that nothing is being hit when requesting static-file.html . 我什至无法击中任何测试console.log语句,所以我知道在请求static-file.html时没有任何击中。 Please see below part of my app.js file: 请参阅我的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"));
}

When I go to production-site.com/static-file.html - I just see the index still, unlike with localhost. 当我转到production-site.com/static-file.html时-与本地主机不同,我仍然看到该索引。

Can anybody help me on that? 有人可以帮我吗? Thanks so much. 非常感谢。

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 */

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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