Setting Up Node and Express Starter Project

Jul 4, 2024

Setting Up Node and Express Starter Project

Overview

  • Setting up a starter project using Node.js and Express.
  • No significant HTMX content yet, only linking to the HTMX library.
  • Optional to skip if comfortable setting up an Express app.
  • Starter project available in course repo (select starter-project branch, download zip, unzip, open in VS Code).

Steps to Set Up the Project

  1. Install Dependencies:
    • Open the terminal in VS Code.
    • Run npm install in the root directory to install dependencies in package.json.
  2. Project Exploration:
    • Folder structure briefly explained.
    • Basics of Express backend present in app.js file.

Breakdown of app.js

  • Imports and App Initialization:
    • Import Express.
    • Create an Express app instance.
  • Middleware:
    • Express URL encoded middleware to parse URL encoded data.
  • Request Handlers:
    • Example of a GET request handler for root URL (/).
    • Accesses request and response objects; currently sends an empty response.
  • Static Middleware:
    • Serve static assets from a public folder.
  • Server Setup:
    • Application listens on port 3000 (visit localhost:3000 to trigger root GET request).

HTML Response with Template Strings

  • Plan to switch empty response to an HTML page.
  • Using JavaScript template strings for HTML to focus on HTMX integration.
  • Create a views folder with a index.js file for HTML templates.

Creating HTML Templates

  • Function for Home Page Template:
    • Create function createHomepageTemplate returning HTML as template string.
  • Setting Up VS Code for HTML in Template Strings:
    • Use inline HTML extension for syntax highlighting and Emmet features.
    • Add comment /* HTML */ before template string for extension to work.
  • Example HTML Template:
    • Grab HTML code from course files; simple structure with a title, styles, and body sections.

Sending HTML Response

  • Import and invoke createHomepageTemplate in app.js to send HTML template as response.
  • Usage of nodemon:
    • Install nodemon globally with npm install -g nodemon.
    • Run app using nodemon app.js to auto-restart server on file changes.

Linking HTMX Library

  • Integrating HTMX:
    • Use CDN link from HTMX documentation.
    • Add script tag in the <head> of HTML template.

Data Setup

  • Data File:
    • data/data.js contains a sample array of book objects.
    • Books have properties like ID, title, and author.
    • Data will be used in upcoming lessons to populate HTML templates.

Next Steps

  • Start using HTMX features in HTML templates in the next lesson.