Serve HTML using Express.js

Berikut merupakan panduan singkat untuk serve file html dengan framework Express.js. Ini dapat digunakan semisal Anda membangun website atau frontend dengan React.

Install Express.js

Install express dengan npm

npm install express

Build

Build frontend agar menjadi file statis index.html berserta css dan js. Lalu pindahkan file ke direktori lain atau ke direktori yang sama dengan script NodeJS.

Buat script app.js lalu edit seperti berikut

const express = require('express');
const path = require('path');

const app = express();
const port = 3000; // You can choose any available port number

// Serve static files from the "public" directory
app.use(express.static(path.join(__dirname, 'public')));

// Serve the index.html file when accessing the root URL
app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'index.html'));
});

// Start the server
app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

Selanjutnya jalankan nodejs script.

node app.js

Terakhir akses http://localhost:3000 melalui browser.