express learning notes (generate project, route, route handler, use mysql, ejs template)

Keywords: MySQL JSON Database SQL

Generation project

Sir, a package.json

cnpm init

Node? Modules folder, which contains the modules provided by node.js

cnpm install

Install Express scaffolding

cnpm i express-generator

Install express

**cnpm install express --save**

Create an Express application named myapp, use ejs template engine, and then install dependency to produce a project

express --view=ejs app

Use the express command to quickly create a project directory from

express app -e

Directory specification

bin: the boot directory contains a boot file www. the default listening port is 3000 (direct node www execution is OK)
node_modules: dependent module packages
 public: store static resources
 routes: route operations
 views: store ejs template engine
 app.js: main file
 package.json: project description file

Route

Express path contains three expressions: string, string pattern and regular expression

A string form

app.get('/',(req,res)=>{
  res.send('This is the front page.')
})

Two string pattern

// This routing path will match 'acd' and 'abcd'. The? Number represents 0 or one.
app.get('/ab?cd',(req,res)=>{
  res.send('This is abcd')
})

// The path of '/ ab+cd' will match 'abcd', 'abbcd', 'abbcd', at least one b

// Plus * for any character

// '/ ab(cd)?e' can be enclosed in brackets

Three regular expression paths

Remember, regular doesn't need Quotes

app.get(/.*fly$/,(req,res)=>{
  res.send('This is abcd')
})

Dynamic routing

Write the dynamic value to the url, and you can get the dynamic value in req

// Using: binding dynamic values
app.get('/news/:id',(req,res)=>{
// This value will exist in req.params.id
 res.send(req.params.id)
})

The name of path parameter must be composed of "literal character" ([A-Za-z0-9]), that is, it cannot be a special character, which will be regarded as the character of normal url
Because hyphens - and dots. Are interpreted literally, they can be used with routing parameters for useful purposes.

// Here this one - as normal characters
Route path: /flights/:from-:to
Request URL: http://localhost:3000/flights/LAX-SFO
req.params: { "from": "LAX", "to": "SFO" }

Route path: /plantae/:genus.:species
Request URL: http://localhost:3000/plantae/Prunus.persica
req.params: { "genus": "Prunus", "species": "persica" }

Dynamic routing can be followed by regular routing

Route path: /user/:userId(\d+)
Request URL: http://localhost:3000/user/42
req.params: {"userId": "42"}

Route handler

In fact, you can use multiple callback functions to do some processing after using the get method

// Next represents the end of execution, and only this next execution will execute the next callback
app.get('/news/:id',(req,res,next)=>{
// Data processing
 req.aa = 'I am pretty.'
 next()
},(req,res)=>{
  res.send(req.params.id + req.aa)
})

Using mysql database

let mysql = require('mysql')

// Create connection
let connection = mysql.createConnection({
  host:'localhost',
  user:'root',
  password:'root',
  database:'shop'
})

// Link up
connection.connect(err =>{
  if (err) {
    console.log(err);
  }else{
    console.log('Link success');
    
  }
})

// sql statement
let strSql = 'select * from user'

// Query
connection.query(strSql,(err,result,fields)=>{
  // result query results
  // fields represents the information of each field queried
  // console.log(result);
  // console.log(fields);
})

// Delete table
// let strSql2 = 'drop table user'
// Delete Library
// let strSql3 = 'drop database shop'
// Create a careate database shop

// insert into user (id,name,sex) values (1, small red, female)
// let strSql4 = 'insert into user (id,name,sex) values (?,?,?)'
// connection.query(strSql4,['3 ','xiaolu','female '], (err, result) = >{
  
// })
// Update data update user set name =?, sex =?
let strSql5 = 'UPDATE user SET name = ?,sex = ? WHERE Id = ?';
connection.query(strSql5,['Minor fertilizer','male',2],(err,result)=>{

})

Using mysql with the server's express project (start)

Write and encapsulate mysql method first

let mysql = require('mysql')

let con = mysql.createConnection({
  host:'localhost',
  user:'root',
  password:'root',
  database:'shop'
})

con.connect(err =>{
  if (err) {
    
  }else{
    console.log('Link success');
  }
})

function aamysql(sqlstr,arr){
  return new Promise( (resolve,reject)=>{
    con.query(sqlstr,arr,(err,data)=>{
      if (err) {
        reject()
      }else{
        resolve(data)
      }
    })
  })
}

module.exports = aamysql

Then use it in the server

let express = require('express')
let aamysql = require('./mysql')
let app = express()
app.get('/', async (req,res)=>{
  let sqlstr = 'select * from teacher';
  let result = await aamysql(sqlstr)
  // console.log(Array.from(result));
  // The json method is to directly change the data into json format, and then send the request
  res.json(result)
})
app.get('/getone/:oneId', async (req,res)=>{
  let sqlstr = 'select * from teacher where id=?';
  let oneId = req.params.oneId;
  // The second parameter of mysql query is in the form of attribute, which is the added or modified value
  let result = await aamysql(sqlstr,[oneId])
  res.json(result)
})
module.exports = app

Combining ejs template

[% XXX% >: js syntax is written in it,
<% = XXX% >: it contains the variables sent by the server to the ejs template after escaping, and the output is the original html
[% - XXX% >: it is also a variable sent by the server to the ejs template, but it will compile the htmt
<% ා comment label, do not execute, do not output content

Conditional statement usage

// js 
app.get('/', async (req,res)=>{
  let sqlstr = 'select * from teacher';
  let result = await aamysql(sqlstr)
  // console.log(Array.from(result));
  // res.json(result)
  // The first parameter is the template file, and the second is the parameter object to be transferred
  let options= {
    gender:'female',
    aa:'Big fool',
    bb:'<a>Little brush</a>'
  }
  res.render('index.ejs',options)
})

// ejs
    <% if(gender == 'male'){%>
      <h1><%- aa%></h1>
    <%}else{%>
      <h1><%- bb%></h1>
    <%}%>

Loop statement

// js
app.get('/', async (req,res)=>{
  let sqlstr = 'select * from teacher';
  let result = await aamysql(sqlstr)
  // console.log(Array.from(result));
  // res.json(result)
  // The first parameter is the template file, and the second is the parameter object to be transferred
  let options= {
    gender:'female',
    aa:'Big fool',
    bb:'<a>Little brush</a>',
    dd:[1,2,3]
  }
  res.render('index.ejs',options)
})

//ejs
    <% for( var i =0;i<dd.length;i++ ){ %>
      <ul>
        <li><%- dd[i] %></li>
      </ul>
    <% } %>
Published 129 original articles, won praise 2, visited 3738
Private letter follow

Posted by mrwutang on Wed, 11 Mar 2020 22:31:25 -0700