Skip to content

Instantly share code, notes, and snippets.

@Mgregchi
Created May 14, 2025 12:36
Show Gist options
  • Save Mgregchi/1085c4560e48f91bbf45517d6f71706c to your computer and use it in GitHub Desktop.
Save Mgregchi/1085c4560e48f91bbf45517d6f71706c to your computer and use it in GitHub Desktop.

🧠 Express.js Handbook for Absolute Beginners

Using Node.js, Express.js & VS Code – For Web Browser Testing Only


📁 Step 1: Project Setup in VS Code

🎯 Goal:

Create a basic Express.js project that runs a web server and responds to browser requests.

✅ Steps:

  1. Open VS Code.

  2. Create a new folder and name it my-express-app.

  3. Open the folder in VS Code:

    • Go to File > Open Folder, select my-express-app.
  4. Open the terminal in VS Code:

    • Use shortcut Ctrl + ` or go to Terminal > New Terminal.
  5. Initialize a Node.js project:

npm init -y

This creates a package.json file, which keeps track of your project's dependencies and metadata.

  1. Install Express:
npm install express

This adds the Express framework (a lightweight web server for Node.js) to your project.

  1. Create your entry file:
touch index.js

This will be your main server file. You’ll write all your code here for now.


🧱 Step 2: Create Your First Server

📜 Code: index.js

// 1. Import express
const express = require('express');

// 2. Create an Express app
const app = express();

// 3. Define a route (when browser accesses "/")
app.get('/', (req, res) => {
  res.send('Hello, World!');
});

// 4. Start the server on port 3000
app.listen(3000, () => {
  console.log('Server running at http://localhost:3000');
});

🧠 Breakdown: What’s Happening?

Line Explanation
const express = require('express'); Loads the Express library so we can use it. Think of Express as a toolkit for building web servers easily.
const app = express(); Creates an "application" — this app will handle incoming requests and give responses.
app.get('/', ...) This defines a "route": when someone opens http://localhost:3000/, this function will run.
res.send('Hello, World!') This sends text back to the browser.
app.listen(3000, ...) Starts the server on port 3000. Open your browser and go to http://localhost:3000.

🌍 Step 3: Add More Pages

Let’s create multiple “pages” using different routes.

app.get('/about', (req, res) => {
  res.send('This is the About page');
});

app.get('/contact', (req, res) => {
  res.send('Contact us at: [email protected]');
});

🔍 Test:

  • Visit http://localhost:3000/about → See “This is the About page”
  • Visit http://localhost:3000/contact → See contact info

🧾 Step 4: Use HTML in Responses

You can also return HTML content:

app.get('/welcome', (req, res) => {
  res.send(`
    <h1>Welcome to My Express App</h1>
    <p>This is an HTML response.</p>
  `);
});

Now http://localhost:3000/welcome will display a styled message.


📁 Step 5: Serve Real HTML Files

Let’s serve a real HTML file instead of writing it in JavaScript.

1. Create a folder for static files:

mkdir public

2. Inside public/, create index.html:

<!-- public/index.html -->
<!DOCTYPE html>
<html>
  <head><title>Home</title></head>
  <body>
    <h1>Welcome!</h1>
    <p>This is from an actual HTML file.</p>
  </body>
</html>

3. Add this to your index.js:

app.use(express.static('public'));

🔍 Result:

Now visit http://localhost:3000/index.html and you’ll see the HTML page.

The browser automatically reads the public/ folder for files like HTML, images, CSS, etc.


❓ What Is a “Route”?

Think of a route as a specific URL path that your app understands.

For example:

URL Route Definition
http://localhost:3000/ app.get('/')
http://localhost:3000/about app.get('/about')
http://localhost:3000/index.html Static file (from public/)

⚠️ Error Handling (Optional for Now)

You can catch errors or send a "404 Page Not Found":

// This runs when no other route matches
app.use((req, res) => {
  res.status(404).send('Page not found');
});

🧪 Test Checklist (In Browser)

URL What You Should See
/ Hello, World!
/about About page
/contact Contact info
/welcome HTML from res.send(...)
/index.html HTML file from public/ folder
/anything-else Page not found

📦 Final Project Structure

my-express-app/
│
├── index.js               # main server code
├── package.json           # npm config
└── public/
    └── index.html         # HTML page to serve

✅ What You’ve Learned

  • How to set up a Node + Express server in VS Code
  • How to create routes that respond to browser URLs
  • How to send text and HTML to the browser
  • How to serve real static HTML files
  • How to view it all in your web browser

📝 Working with Forms in Express.js

Using HTML + Express.js + VS Code (View in Browser)


📌 Goal

You’ll build a simple web page with a form (e.g., a name input), submit it, and have your Express server process the form data and respond with a custom message.


🧱 Step-by-Step: Form Handling with Express


1️⃣ Create a Form Page

Inside your public/ folder, create a new file:

touch public/form.html

✏️ Code: public/form.html

<!DOCTYPE html>
<html>
  <head>
    <title>Form Example</title>
  </head>
  <body>
    <h1>Submit Your Name</h1>
    <form action="/submit" method="POST">
      <label for="name">Your Name:</label>
      <input type="text" id="name" name="name" required />
      <br><br>
      <button type="submit">Submit</button>
    </form>
  </body>
</html>

🧠 What’s happening?

  • <form action="/submit" method="POST"> Tells the browser to send form data to http://localhost:3000/submit using the POST method.
  • The name="name" part is important — it defines the key sent to the server.

2️⃣ Enable Form Data Parsing in Express

Update your index.js to allow Express to read form submissions.

✅ Code: Add at the top of your index.js

app.use(express.urlencoded({ extended: true }));

🧠 Why this?

This built-in middleware helps Express read data sent from forms (application/x-www-form-urlencoded format, which is the default for HTML forms).


3️⃣ Handle the Form Submission

Add this route to your index.js:

app.post('/submit', (req, res) => {
  const userName = req.body.name;
  res.send(`<h1>Hello, ${userName}!</h1><p>Thanks for submitting the form.</p>`);
});

🧠 Explanation:

  • req.body.name gets the value from the <input name="name"> field in your form.
  • The server sends back a personalized greeting.

📂 Your Updated index.js (Full Sample)

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

// Allow Express to read form data
app.use(express.urlencoded({ extended: true }));

// Serve static files from "public" folder
app.use(express.static('public'));

// Show greeting when form is submitted
app.post('/submit', (req, res) => {
  const userName = req.body.name;
  res.send(`<h1>Hello, ${userName}!</h1><p>Thanks for submitting the form.</p>`);
});

// Optional: Handle not found
app.use((req, res) => {
  res.status(404).send('Page not found');
});

// Start server
app.listen(3000, () => {
  console.log('Server running at http://localhost:3000');
});

🔍 Test in Browser

  1. Start your server:

    node index.js
  2. Go to http://localhost:3000/form.html

  3. Enter a name and click Submit.

  4. You’ll see a personalized greeting like:

Hello, Alice!
Thanks for submitting the form.

✅ What You Just Learned

Concept What It Means
HTML <form> Sends user input to the server
POST route Server endpoint that receives form data
express.urlencoded() Middleware that parses form input
req.body Contains submitted form data

💡 What’s Next?

Here are a few ideas you can try:

  1. Add more fields (email, message, age, etc.)
  2. Create a Thank You page instead of showing response directly
  3. Validate input on the server (e.g. make sure name isn’t empty)
  4. Save data to a file or database (future lesson)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment