Express.js -- Introduction

setup

  • Create project folder
  • cd. into the folder and run "npm i -g express-generator" to install project generator globally
  • run "express" to generate project in the project folder
    • option "--view=hbs" sets up the view template (hbs = handlebars.js)
  • run "npm install" install all dependencies
  • run "npm start" to start the server

project structure

  • views folder
    • contains templates
    • layout.hbs is the default page layout
  • routes folder
    • contains initial routing setup
  • public directory
    • contains assets
    • stylesheets (css), images, etc.
  • bin directory
    • contains www script
    • www: a Node.js script that
      • initializes the HTTPServer objects
      • starts listening to port
      • uses app.js
var app = require('../app'); 
... 
var port = normalizePort(process.env.PORT || '3000'); 
app.set('port', port); 
... 
var server = http.createServer(app); 
... 
server.listen(port); 
server.on('error', onError); 
server.on('listening', onListening); 
  • port is set by calling normalizePort, default port 3000, override by setting env.PORT
    • i.e. PORT = 4242 npm start // changes port to 4242, uppercase port
  • HTTPserver object is created using app.js configuration

app.js

This is where you configure your application object and export it.

app.set

Set the application properties

example

app.set('views', path.join(__dirname, 'views')); 
app.set('view engine', 'hbs');

 routing

Routing refers to how an application’s endpoints (URIs) respond to client requests.

2 ways to handle requests:

  • By Methods: app.all(all methods), app.get, app.post, etc.

  • By using Middleware: app.use
  • Routing methods use callback functions:

the application “listens” for requests that match the specified route(s) and method(s), and when it detects a match, it calls the specified callback function.

  • Express supports multiple callbacks:
    • Specify next as an argument to the callback function and then call next() within the body of the function to hand off control to the next callback.

app.use

Set the middleware functions that are executed during the processing of requests.

e.g. body-parser, cookie-parser

example

app.use(bodyParser.json()); 
app.use(bodyParser.urlencoded({ extended: false })); 
app.use(cookieParser()); 

middleware

Middleware are functions that are involved in processing requests and sending results to HTTP clients

request processing cycle

  1. incoming request
  2. 0+ middleware
  3. router function
  4. response sent

4 possible actions

  • Executes its own business logic

  • Modifies the request or response objects. (body-parser and
    cookie-parser)

  • Calls next to proceed to the next middleware function or otherwise signals an error.

  • Sends a response, ending the cycle. i.e. res.send()

middleware arguments

  • 1st: match URL pattern (optional)
  • 2nd: function
    • request
    • response
    • next: callback function
      • report error -- next(error)
      • pass control to next middleware

matching methods

use app.METHOD instead of app.use

e.g. app.put --> http.put methods; app.get --> http.get methods

  • app.get: responde with "hello world" when a get request is m
app.get('/', function (req, res) {
   res.send('hello world')
})

router middleware

A type of middleware used explicitly for routing requests based on their URL

creating router module

  • in routes module
  • create .js file
  • define router
  • export
var express = require('express');
var router = express.Router();

// matching routes
router.get('/login', ...)

module.exports = router;

using router module

  • in app.js
  • import module
  • app.use
var indexRouter = require('./routes/index');

app.use('/home', indexRouter);

matching url

in the example above, /home/login will match to the indexRouter.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值