Skip to main content
  1. Posts/

Serve HTML using Express.js

·1 min·
nodejs html nodejs
Table of Contents

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.

Related

Command 'ng' not found pada Angular
·1 min
nodejs angular nodejs
Error [ERR_REQUIRE_ESM] NodeJS CPanel
·1 min
nodejs cpanel nodejs
Fix Knex: run $ npm install mysql2 --save EEXIST: file already exists
·1 min
nodejs nodejs
PM2 Quick Start
·2 mins
nodejs nodejs pm2
Cara Membuat iFrame HTML
·1 min
html php html
Deploy Angular di cPanel
·1 min
cpanel nodejs cpanel angular