Matt
Matt

Reputation: 551

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.

I have this working locally, so when I go to localhost:3000/static-file.html, I can see the file. 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. Please see below part of my app.js file:

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.

Can anybody help me on that? Thanks so much.

Upvotes: 0

Views: 88

Answers (1)

Rahul kumar
Rahul kumar

Reputation: 44

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

Upvotes: 1

Related Questions