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

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

  1. Good website! I really love how it is simple on my eyes and the data are well written. I’m wondering how I could be notified whenever a new post has been made. I have subscribed to your RSS which must do the trick! Have a nice day!

    Reply

Leave a Comment