點燈坊

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

Express Overview

Sam Xiao's Avatar 2022-11-16

Express is a backend web framework for Node. We can use Express to build Web Server and REST API.

Version

Express 4.18.2

Add Library

$ npm install express cors
$ npm install -D nodemon prettier
  • express:Web framework for Node
  • cors:prevent CORS for Same-Origin Policy
  • nodemon:reload when code is modified
  • prettier:code formater for JavaScript

NPM Script

package.json

{
  "type": "module",
  "name": "express-lab",
  "version": "1.0.0",
  "scripts": {
    "dev": "nodemon app.js"
  },
  "dependencies": {
    "cors": "^2.8.5",
    "express": "^4.18.2"
  },
  "devDependencies": {
    "nodemon": "^2.0.20",
    "prettier": "^2.7.1"
  }
}
  • dev:use nodemon to start Express

app.get()

import express from 'express'
import cors from 'cors'

let app = express()
app.use(cors())

app.get('/api', (req, res) => res.send('Hello World'))
app.listen(8080, () => console.log('Node listen on port: 8080'))

Line 4

let app = express()
  • Use express() to create an app Object

Line 5

app.use(cors())
  • Use cors middleware

Line 7

app.get('/api', (req, res) => res.send('Hello World'))
  • app.get():create REST GET

Line 8

app.listen(8080, () => console.log('Node listen on port: 8080'))
  • Start Express on port 8080

Start Node

$ npm run dev
  • Start Express

get001

HTTP Client

get000

Conclusion

  • These are the smallest packages set for Express

Reference

Express, Installing