+1

[Node.js] Creating Webserver (p2)

I. Partial views

  • Partials are views designed to be used from within other views.

  • They can be reused across multiple views.

  • Example of a partial view

// partials/navbar.ejs
<nav>
    <ul>
        <li>
            <a href="/">Home</a>
        </li>
         <li>
            <a href="/">Blog</a>
        </li>
    </ul>
</nav>
  • Include navbar.ejs partial to home.ejs: <%- include('partials/navbar') %>

II. Serve static files with middleware

1. Middleware

  • Middleware are functions which run between request and response cycle, it has access to the request object(req), the response object(res).
  • Middleware functions can be used to:
    • Execute any code.
    • Make changes to the request and the response objects.
    • End the request-response cycle.
    • Call the next middleware function in the stack.
  • If the current middleware function does not end the request-response cycle, it must call next() to pass control to the next middleware function. Otherwise, the request will be left hanging.

2. Types of middleware in Express

  • Application-level middleware
    • app.use() : binds a middleware to an instance of app obj
  • Router-level middlwware
  • Error-handling middleware
  • Built-in middleware
    • express.static(root, [options]): serves files in root directory as static assets
  • Third-party middleware

3. Serve static files (images, css, js)

  • To serve static files we need to use express.static middleware.
  • We can call middleware function multiple times to serve multiple static assets directory.
app.use('path-to-assets/static-file', (req,res,next){
    // logic
 }
 // serves images, css and js files in public folder 
 // so you can load http://localhost:3000/css/style.css
 app.use(express.static('public'));
 app.use(express.static('files')
  • Create virtual path (path does not actually exist in the file system) for files served by express.static.
app.use('static', express.static('public'));
// now you can load http://localhost:3000/static/css/style.css
// if you run app from another dir, its safer to use absolute path for the folder you want to serve:
const path = require('path')
app.use('/static', express.static(path.join(__dirname, 'public')))

III. Handle post requests

  • POST request is used to ask server to accept/store data which is enclosed in the body of rqe obj.
  • Often used when user submits forms: <form method='POST' action='/contact'>

1. body-parse

  • body-parser is used to parse incoming request bodies in a middleware before your handlers, available under the req.body property.
  • Installation: body-parse middleware: npm install body-parse
  • To use the middleware we need to require it: const bodyParser = require('body-parser');
  • There are 4 types of data parser:
    • JSON body parser: bodyParser.json([options]) returns middlware only parses json
    • Raw body parser: bodyParser.raw([options]) returns middlware parses all bodies as a Buffer
    • Text body parser: bodyParser.text([options]) returns middlware parses all bodies as a string
    • URL-encoded form body parser: bodyParser.urlencoded([options]) returns middlware parses urlencoded bodies, accepts only UTF-8 encoding, returns new body obkect which contains key-value pairs.

2. code to handle post request

    <form method='POST' action='/contact'>
        <input type="text"  name="name" placeholder="Enter your name...">
        <input type="text"  name="age" placeholder="Enter your age...">
        <input type="submit" value="Submit">
    <form>
const bodyParser = require('body-parser');
// invokes middleware to parse POST data
const urlencodedParser = bodyParser.urlencoded({ extended: false });

// adding body parser to /contact root, whenever there is a post request to this route the middleware is fired to handle data
// urlencodedParser: parses data from form and stores it in req.body
app.post('/contact', urlencodedParser, (req, res) => {
    if(!req.body) {
        // handle when data is not ready
    } else {
        // data => { "name": "vivian", "age" : "xx"}
    }
})


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí