Getting Started
Hello World {.row-span-2}
- 
"Create project, add package.jsonconfiguration$ mkdir myapp # create directory $ cd myapp # enter the directory $ npm init -y # Initialize a configuration
- 
Install dependencies $ npm install express
- 
Entry file index.jsadd code:const express = require('express') const app = express() const port = 3000 app.get('/', (req, res) => { res. send('Hello World!') }) app. listen(port, () => { console.log(`Listening port on ${port}`) })
- 
Run the application using the following command $ node index.js
{.marker-timeline}
express -h {.row-span-2}
Usage: express [options] [dir]
Options:
  -h, --help output usage information
      --version output version number
  -e, --ejs add ejs engine support
      --hbs add hbs engine support
      --pug add pug engine support
  -H, --hogan add hogan.js engine support
      --no-view No view engine generated
  -v, --view <engine> add view <engine> support (ejs|hbs|hjs|jade|pug|twig|vash) (default jade)
  -c, --css <engine> add stylesheet <engine> support (less|stylus|compass|sass) (default css)
      --git add .gitignore
  -f, --force force non-empty directories{.wrap-text}
Create a myapp project
$ express --view=pug myapp
# run the application
$ DEBUG=myapp:*npm startexpress()
| :- | :- | 
|---|---|
| express.json() | # (opens in a new tab) | 
| express.raw() | # (opens in a new tab) | 
| express.Router() | # (opens in a new tab) | 
| express.static() | # (opens in a new tab) | 
| express.text() | # (opens in a new tab) | 
| express.urlencoded() | # (opens in a new tab) | 
Router
| :- | :- | 
|---|---|
| router.all() | # (opens in a new tab) | 
| router.METHOD() | # (opens in a new tab) | 
| router.param() | # (opens in a new tab) | 
| router.route() | # (opens in a new tab) | 
| router.use() | # (opens in a new tab) | 
Application
var express = require('express')
var app = express()
 
console.dir(app.locals.title)
//=> 'My App'
console.dir(app.locals.email)
//=> 'me@myapp.com'Attribute
| :- | :- | 
|---|---|
| app.locals | Local variables in the application # (opens in a new tab) | 
| app.mountpath | Path pattern for mounting sub-apps # (opens in a new tab) | 
Events
| :- | :- | 
|---|---|
| mount | The child application is mounted on the parent application, and the event is triggered on the child application # (opens in a new tab) | 
Method
| :- | :- | 
|---|---|
| app.all() | # (opens in a new tab) | 
| app.delete() | # (opens in a new tab) | 
| app.disable() | # (opens in a new tab) | 
| app.disabled() | # (opens in a new tab) | 
| app.enable() | # (opens in a new tab) | 
| app.enabled() | # (opens in a new tab) | 
| app.engine() | # (opens in a new tab) | 
| app.get(name) | # (opens in a new tab) | 
| app.get(path, callback) | # (opens in a new tab) | 
| app.listen() | # (opens in a new tab) | 
| app.METHOD() | # (opens in a new tab) | 
| app.param() | # (opens in a new tab) | 
| app.path() | # (opens in a new tab) | 
| app.post() | # (opens in a new tab) | 
| app.put() | # (opens in a new tab) | 
| app.render() | # (opens in a new tab) | 
| app.route() | # (opens in a new tab) | 
| app.set() | # (opens in a new tab) | 
| app.use() | # (opens in a new tab) | 
Request
Attribute
| :- | :- | 
|---|---|
| req.app | # (opens in a new tab) | 
| req.baseUrl | # (opens in a new tab) | 
| req.body | # (opens in a new tab) | 
| req.cookies | # (opens in a new tab) | 
| req.fresh | # (opens in a new tab) | 
| req.hostname | # (opens in a new tab) | 
| req.ip | # (opens in a new tab) | 
| req.ips | # (opens in a new tab) | 
| req.method | # (opens in a new tab) | 
| req.originalUrl | # (opens in a new tab) | 
| req.params | # (opens in a new tab) | 
| req.path | # (opens in a new tab) | 
| req.protocol | # (opens in a new tab) | 
| req.query | # (opens in a new tab) | 
| req.route | # (opens in a new tab) | 
| req.secure | # (opens in a new tab) | 
| req.signedCookies | # (opens in a new tab) | 
| req.stale | # (opens in a new tab) | 
| req.subdomains | # (opens in a new tab) | 
| req.xhr | # (opens in a new tab) | 
Method
| :- | :- | 
|---|---|
| req.accepts() | # (opens in a new tab) | 
| req.acceptsCharsets() | # (opens in a new tab) | 
| req.acceptsEncodings() | # (opens in a new tab) | 
| req.acceptsLanguages() | # (opens in a new tab) | 
| req.get() | Get HTTP request header fields # (opens in a new tab) | 
| req.is() | # (opens in a new tab) | 
| req.param() | # (opens in a new tab) | 
| req.range() | # (opens in a new tab) | 
Response
app.get('/', function (req, res) {
  console.dir(res.headersSent) //false
  res.send('OK')
console.dir(res.headersSent) //true
})Attribute
| :- | :- | 
|---|---|
| res.app | # (opens in a new tab) | 
| res.headersSent | # (opens in a new tab) | 
| res.locals | # (opens in a new tab) | 
Method
| :- | :- | 
|---|---|
| res.append() | # (opens in a new tab) | 
| res.attachment() | # (opens in a new tab) | 
| res.cookie() | # (opens in a new tab) | 
| res.clearCookie() | # (opens in a new tab) | 
| res.download() | Prompt for files to download # (opens in a new tab) | 
| res.end() | end the response process # (opens in a new tab) | 
| res.format() | # (opens in a new tab) | 
| res.get() | # (opens in a new tab) | 
| res.json() | Send JSON response # (opens in a new tab) | 
| res.jsonp() | Send a response with JSONP support # (opens in a new tab) | 
| res.links() | # (opens in a new tab) | 
| res.location() | # (opens in a new tab) | 
| res.redirect() | Redirect request # (opens in a new tab) | 
| res.render() | render view template # (opens in a new tab) | 
| res.send() | Send various types of responses # (opens in a new tab) | 
| res.sendFile() | Send a file as an octet stream # (opens in a new tab) | 
| res.sendStatus() | # (opens in a new tab) | 
| res.set() | # (opens in a new tab) | 
| res.status() | # (opens in a new tab) | 
| res.type() | # (opens in a new tab) | 
| res.vary() | # (opens in a new tab) | 
Example
Router {. row-span-2}
Called for any request passed to this router
router. use(function (req, res, next) {
  //.. some logic here .. like any other middleware
  next()
})will handle any request ending in /events
//depends on where the router "use()"
router. get('/events', (req, res, next) => {
  //..
})Response
The res object represents the HTTP response sent by the Express application when it receives an HTTP request
app.get('/user/:id', (req, res) => {
  res.send('user' + req.params.id)
})Request
A req object represents an HTTP request and has properties for the request query string, parameters, body, HTTP headers, etc.
app.get('/user/:id', (req, res) => {
  res.send('user' + req.params.id)
})res. end()
res. end()
res.status(404).end()End the response process. This method actually comes from the Node core, specifically the response.end() method of http.ServerResponse
res.json([body])
res.json(null)
res.json({ user: 'tobi' })
res.status(500).json({ error: 'message' })app.all
app.all('/secret', function (req, res, next) {
  console.log('access secret section...')
  next() // Pass control to the next handler
})app.delete
app.delete('/', function (req, res) {
  res.send('DELETE request to homepage')
})app.disable(name)
app.disable('trust proxy')
app.get('trust proxy')
// => falseapp.disabled(name)
app.disabled('trust proxy')
// => true
 
app.enable('trust proxy')
app.disabled('trust proxy')
// => falseapp.engine(ext, callback)
var engines = require('consolidate')
 
app.engine('haml', engines.haml)
app.engine('html', engines.hogan)app.listen([port[, host[, backlog]]][, callback])
var express = require('express')
 
var app = express()
app.listen(3000)Routing
const express = require('express')
const app = express()
 
//Respond to "hello world" when making a GET request to the homepage
app.get('/', (req, res) => {
  res.send('hello world')
})// GET method routing
app.get('/', (req, res) => {
  res.send('GET request to the homepage')
})
 
// POST method routing
app.post('/', (req, res) => {
  res.send('POST request to the homepage')
})Middleware
function logOriginalUrl (req, res, next) {
  console.log('ReqURL:', req.originalUrl)
  next()
}
 
function logMethod (req, res, next) {
  console.log('Request Type:', req.method)
  next()
}
 
const log = [logOriginalUrl, logMethod]
 
app.get('/user/:id', log,
  (req, res, next)=>{
    res.send('User Info')
  }
)Using templates
app.set('view engine', 'pug')Create a Pug template file named index.pug in the views directory with the following content
html
  the head
    title= title
  the body
    h1=messageCreate a route to render the index.pug file. If the view engine property is not set, the extension of the view file must be specified
app.get('/', (req, res) => {
  res. render('index', {
    title: 'Hey', message: 'Hello there!'
  })
})