Node.js 1) Initiating, Express Framework

Node.js 1) Initiating, Express Framework

After installing Node.js..

  • npm init // entry point: server.js
    • npm : Use to install libraries
    • npm init : Make package.json
    • package.json : Automatically records which libraries are used

What is Express?

  • Express is the most used Node.js server framework
  • $ npm install express
  • add below code in app.js / router / any other js file that requies express
    var express = require("express");
    // or
    import express from "express";
    

Express Routing

Routing refers to determining how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, and so on).

Structure : app.METHOD(PATH, HANDLER)

  • app is an instance of express.
  • METHOD is an HTTP request method, in lowercase.
  • PATH is a path on the server.
  • HANDLER is the function executed when the route is matched.
// Example
import express from "express";

const app = express();
const port = 3000;

app.get("/", (req, res) => {
  res.send("Hello World!");
});

app.listen(port, () => {
  console.log(`App is running on http://localhost:${port}`);
});

Static files in Express

  • Use express.static middleware function in Express to serve static files such as images, CSS files, and JavaScript files.
  • express.static(root, [options])
    // Example
    app.use("/static", express.static(__dirname + "/public"));
    
  • "/static" : Create virtual path prefix (where path does not exist in the file system) for files that are served by the express.
  • __dirname : It is safer to use absolute path if you run the express app from another directory

Reference :
-kyun2da.github.io
-expressjs.com