Chapter one establishes the local basic environment for front-end full stack development

1-1 Course introduction

  • Preparation of the development environment

    1. The installationNodejs
    2. The first oneNodejsThe program
    3. Nodejsnpmintroduce
    4. introducenodemonTo achieve hot start
    5. usenrmTo solvenpmThe source of the problem
    6. usenvmmanagementNodejsVersion of the problem
  • WebApplication base

    1. WebApplication andExpressintroduce
    2. useExpressBuild the first oneWebservice
    3. Routing (Routing)
    4. Middleware (Middleware) introduction and use
    5. Custom authoring middleware
    6. Exception handling
    7. MysqlInstallation and use of basic commands
    8. ORMThe frameworkSequelizeIntroduction and Use
  • Actual project (Todo)

  • Sorting and summarizing

1 to 2NodeJSThe installation

  1. Download the official installation package
  2. inmac osThrough theHomebrewThe installation
  3. usenvmVersion Manager Installation (recommended)

1-3 firstNodejsThe program

win.js

const win = require('os');

// Displays system CPU information
console.log(win.cpus());

// Displays the percentage of memory remaining in the system
const freemen = win.freemem()/1024/1024/1024; //byte KB MB GB
const totalmem = win.totalmem()/1024/1024/1024; //byte KB MB GB
console.log('freemen/totalmem:'.parseInt(freemen/totalmem*100));

// Displays the network status of the current system
console.log(win.networkInterfaces());

console.log(win.arch());
console.log(win.platform());
console.log(win.release());
console.log(win.type());
console.log(win.userInfo());
console.log(win.loadavg());
Copy the code

server.js

// The first nodejs program

const http = require('http');
const hostname = '127.0.0.1';
const port = "50000";

// Create a server instance
const server = http.createServer((req, res) = > {
  // req: request object
  // res: response object
  res.statusCode = 200;
  res.setHeader('Content-Type'.'text/plain');
  res.end('hello node');
})

server.listen(port, hostname, () = > {
  / / callback
  console.log('Service started successfully, listening port:${port}`);
})

// Start the service node server.js
Copy the code

1-4 Nodejsnpmintroduce

From 1 to 5NodemonIntroduction and Use

  • This section describes the Nodemon features

  • Project integration and configuration demonstration

    • Project execution

      npm install nodemon -D
      Copy the code
    • Modify the startup command in package.json

      "scripts": {
          "dev:node": "node ./src/index.js"."dev": "nodemon ./src/index.js"."test": "echo \"Error: no test specified\" && exit 1"
        },
      Copy the code

- First line: Print the version of 'Nodemon' - second line: Enter 'RS' to restart the project - third line: - Modify the path of 'watch' through the 'nodemon.json' file. Under the project, create the 'nodemon.json' file > nodemon.json {"watch": [". / SRC / * * / *. * "]} ` ` ` - the fourth row: listening ` js ` ` MJS ` ` json ` fileCopy the code

1-6 nrmnvmIntroduction to the use of

usenrmmanagementnpm

  • Install NRM globally using NPM

    npm install nrm -g
    Copy the code
  • Use the following command to view the NPM source

  • nrm ls
    Copy the code

npm ——– registry.npmjs.org/

yarn ——- registry.yarnpkg.com/

cnpm ——- r.cnpmjs.org/

taobao —– registry.npm.taobao.org/

nj ——— registry.nodejitsu.com/

npmMirror — skimdb.npmjs.com/registry/

edunpm —– registry.enpmjs.org/

  • Use the following command to viewnrmCommon commands of
  • nrm -h
    Copy the code
ls List all the registries current Show current registry name use <registry> Change registry to registry add <registry> < URL > [home] Add one custom Registry (use this command when using private sources)Copy the code

usenvmmanagementnodejsversion

  • windowsInstall the reference

Github.com/coreybutler…

  • Run the following command to check the node version

    nvm ls
    Copy the code
  • Run the following command to view common NVM commands

  • nvm -h
    Copy the code
NVM ls Views all installed NodeJS versionsCopy the code

NVM install Version You can install a specified nodeJS version. NVM Use the version number to switch to the specified version. NVM uninstall Version number To uninstall the specified version

The second chapterWebApplication base

2-1 WebApplication basis andExpressintroduce

  • What is a Web application

    Provide API services called Web applications EG: front-end (Ajax/AS/Up —-> Server (Web applications) —-> Cache/database)

  • The role of Express in Web applications

    Build HTTP service, accept REQ to process RES, and defend against attack routing

    A Web framework in Node

  • Build a Web application using Express

    • Create the Express project directory

      mkdir express-myapp

      cd express-myapp

    • Use the following commands to create the package.json file and.git folder, and create the.gitignore file

      .DS_Store node_modules/ /dist/ npm-debug.log* yarn-debug.log* yarn-error.log* static/mock # Editor directories and files  .idea .vscode *.suo *.ntvs* *.njsproj *.slnCopy the code

      npm init -y

      git init

    • Use the following command to download and install Express and save it to the dependency list

      npm install express -S

    • Create a SRC folder under your project and create an index.js file under the folder

      index.js

      / / into the express
      const express = require('express')
      // Create expres instance
      const app = express()
      
      const port = 3000
      
      / / http://127.0.0.1:3000
      // app.use((req, res) => {
      // res.json({
      // name: 'vience'
      / /})
      // })
      
      / / http://127.0.0.1:3000/name
      app.get('/name'.(req, res) = > {
        let {age} = req.params
        res.send('vience')
      })
      
      app.get('/name/:age'.(req, res) = > {
        let {age} = req.params
        res.json({
          name: 'vience',
          age
        })
      })
      
      app.post('/name'.(req, res) = > {
        let {age} = req.params
        res.send('vience_post')
      })
      
      app.listen(port, () = > {
        console.log(`Example app listening on port ${port}! `)})Copy the code
    • If nodemon is used to start the project, see 1-5 for installation and configuration

2-2 RouteIntroduction and Use

  • RouteWhat is the

Route means determining how an application responds to a client’s request for a particular endpoint (URL > network > DNS resolution > destination server > Routing).

Specific endpoints are URIs (or paths) and specific HTTP request methods

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

app.METHOD(PATH, HANDLER)
Copy the code
  • appYes.expressThe instance.
  • METHODIs a lowercase HTTP request method (get post put delete)
  • PATHIs the path on the server.
  • HANDLERIs the function performed when matching routes.

2-3 ExpressRouting demo

Write the following code in the index.js file from the previous project

  • By the method type requestedget / post / put / delete
app.get('/demo'.function (req, res) {
    res.json({
        message: 'Hello Express Route from get demo'})})Copy the code
app.post('/demo'.function (req, res) {
    res.json({
        message: 'Hello Express Route from post demo'})})Copy the code
  • Through the URI
/ / GET http://127.0.0.1:3000/user/byname? name=vience
app.get('/user/byname'.function (req, res) {
  let { name } = req.query
  res.json({
      name
  })
})
Copy the code
/ / GET http://127.0.0.1:3000/user/byid? id=10001
app.get('/user/byid'.function (req, res) {
  let { id } = req.query
  res.json({
      id
  })
})
Copy the code

2-4 ExpressroutingAPIuse

App. All is used

  • Need to define an API/route that allows the client to get a response regardless of the request type (get/ POST/DELETE/PUT)

    / / GET/POST/DELETE/PUT http://127.0.0.1:3000/demo1
    app.all('/demo1'.(req, res) = > {
      res.json({
        message: 'demo1'.method: req.method
      })
    })
    Copy the code
  • You need to define an API/route that allows the client to get a response no matter what request URI it uses (logging)

    / / GET/POST/DELETE/PUT http://127.0.0.1:3000/ *
    app.all(The '*'.(req, res) = > {
      res.json({
        message: 'demo1'.method: req.method,
        URI: req.path
      })
    })
    Copy the code

2-5 ExpressroutingAPIuse

Use of app.use –> Middleware

  • Need to define an API/route that allows the client to get a response regardless of the request type (get/ POST/DELETE/PUT)

     / / GET/POST/DELETE/PUT http://127.0.0.1:3000/demo1
      app.use('/demo2'.(req, res) = > {
        res.json({
          message: 'demo2'.method: req.method
        })
      })
    Copy the code
  • Need to define an API/route that allows the client to get a response no matter what request URI it uses

    / / GET/POST/DELETE/PUT http://127.0.0.1:3000/ *
    app.use((req, res) = > {
      res.json({
        message: 'demo1'.method: req.method,
        URI: req.path
      })
    })
    Copy the code
  • Cutting and using routes

    • Requirements: Existing order module routing and membership module routing

      1. First, create router folder under SRC, and create two routing modules member.js and oeder

      2. The code in the file is as follows

        member.js

        const express = require('express');
        
        const router = express.Router();
        
        router.get('/list'.(req, res) = > {
          res.json({
            list: [{id: 001.name: 'bill'
              },
              {
                id: 002.name: 'Joe'}]})})module.exports = router;
        Copy the code

        order.js

        const express = require('express');
        
        const router = express.Router();
        
        router.get('/list'.(req, res) = > {
          res.json({
            list: [{id: 001.price: 200.name: 'shoes'
              },
              {
                id: 002.price: 500.name: 'baby'}]})})module.exports = router;
        Copy the code
      3. Import the two routing modules (middleware) in index.js as follows

        // Route cutting and usage
        / / GET http://127.0.0.1:3000/member/list
        const memberRouter = require('./router/member');
        app.use('/member', memberRouter)
        / / GET http://127.0.0.1:3000/order/list
        const orderRouter = require('./router/order');
        app.use('/order', orderRouter)
        Copy the code

2-6 Introduction and use of middleware

  • What is Express middleware

    Pluggable function

    Middleware architecture

    1. A function
    2. Err, req, res, next,

    function

    1. Exception handling
    2. Handle the business functions, then hand over control –> Next
    3. Respond to the request — end the response –> as a handler for the route

    level

    1. App-level usage (global)
      • When you sign up, it’s at the top
      • App.use –> API loaded in
    2. router jibie
    3. Exception Handling –> APP level
    4. Built-in level
  • Built-in middleware and third-party middleware

  • Custom middleware

2-7 Exception Handling

  • Exception handling
  • Express built-in exception handling
  • Custom exception handling