How to connect to a Node.js server that's using Express using an HTML file?

You run a node.js express server on LocalHost or a service provider (Heroku, AWS). How do I connect this to my website?

E.G — You go to..
www.yourdomain.com -> Connects to HEROKU server -> HEROKU server sends html file

app.js

const http      = require('http'),
      path      = require('path'),
      express   = require('express'),
      app       = express(),
      serv      = require('http').Server(app);

var htmlPath = path.join(__dirname, 'client');

app.use(express.static(htmlPath));

app.get('/', (req, res) => {
    res.sendFile(htmlPath + '/index.html');
});

var server = serv.listen(2000, () => {
    var host = 'localhost';
    var port = server.address().port;
    console.log(`listening on http://${host}:${port}/`);
});

In this case, now instead of going to localhost:2000 directly to receive the index.html file, you go to yourdomain.com and the server sends the index.html file

9 thoughts on “How to connect to a Node.js server that's using Express using an HTML file?”

  1. You need to set the DNS system to redirect to the public IP of the machine hosting the Express application. The express application needs to also be listening for GET requests sent to the path you are specifying.

    You would also need to configure the firewall on that machine to allow port 80 and 443 to be open.

    Reply

Leave a Comment