Express

字数 390 · 2020-04-28

#javascript

Hello World

1
2
3
4
5
6
7
const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => res.send('Hello World!'))

app.listen(port, () => console.log(`Example app listening at http://localhost:${port}`))

Generator

1
npx express-generator
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
├── app.js
├── bin
│   └── www
├── package.json
├── public
│   ├── images
│   ├── javascripts
│   └── stylesheets
│       └── style.css
├── routes
│   ├── index.js
│   └── users.js
└── views
    ├── error.jade
    ├── index.jade
    └── layout.jade

Basic routing

Each route can have one or more handler functions, which are executed when the route is matched.

Route definition takes the following structure:

1
app.METHOD(PATH, HANDLER)

Serving static files

To serve static files such as images, CSS files, and JavaScript files, use the express.static built-in middleware function in Express.

1
express.static(root, [options])

To use multiple static assets directories, call the express.static middleware function multiple times:

1
2
app.use(express.static('public'))
app.use(express.static('files'))

If you run the express app from another directory, it’s safer to use the absolute path of the directory that you want to serve:

1
app.use('/static', express.static(path.join(__dirname, 'public')))