點燈坊

失くすものさえない今が強くなるチャンスよ

Using Express as a Web Server

Sam Xiao's Avatar 2022-07-29

Not only using Express as API Server but also Web Server for static HTML.

Version

Node 16.16.0
Express 4.17.1

HTML

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Title</title>
  </head>
  <body>
    Hello World
  </body>
</html>

A simple HTML file for Hello World.

overview000

index.html is located under the dist directory of the project.

Express

package.json

{
  "type": "module",
  "name": "express-lab",
  "version": "0.0.0",
  "dependencies": {
    "express": "^4.17.1",
  },
  "devDependencies": {
    "nodemon": "^2.0.13",
  },
  "scripts": {
    "dev": "nodemon app.js",
  }
}
  • express:a framework for web service
  • nodemon:restart the app when code is modified

app.js

import express from "express";
import { dirname, join } from "path";
import { fileURLToPath } from "url";

let file = fileURLToPath(import.meta.url);
let dir = dirname(file);

let app = express();
app.use(express.static(join(dir, 'dist')));

app.listen(8080, () => console.log("Node listen on port: 8080"));

Line 1

import express from "express";
import { dirname, join } from "path";
import { fileURLToPath } from "url";
  • Import express from express module
  • Import dirname()join() from path module
  • Import fileURLToPath() function from url module

Line 5

let file = fileURLToPath(import.meta.url);
  • import.meta.url:get the file URL of the current module. For example: file:///Users/oomusou/code/express/express-lab/app.js

  • **fileURLToPath()**:return the fully-resolved platform-specific Node file path. For example: /Users/oomusou/code/express/express-lab/app.js

Line 6

let dir = dirname(file);
  • **dirname()**:return the directories from a file path

Line 8

let app = express();
  • express():create an Express object

Line 9

app.use(express.static(join(dir, 'dist')));
  • Use the dist directory as the home directory of the Web
  • All HTML files are located under the dist directory

Line 11

app.listen(8080, () => console.log("Node listen on port: 8080"));
  • Express is running on port 8080

Conclusion

  • When using Express as an API server, we can also provide web service for HTML. This makes both API and HTML use the same port to prevent the CORS problem