Remaining content

  • Back-end Nginx reverse proxy

  • On-line configuration

  • Expree rewrite

  • Koa2 rewrite

One: front-end style

Home [Not logged in]

My blog page

Edit/add pages

Details page

Two: Simple database configuration

My_blog database

Create a blogs table, Users table.

Id auto-growth, primary key, int, cannot be null

Createtime bigInt (20) createTime bigInt (20)

The user table

Three: Node project directory

all

Node – blog directory

  • Module: Encapsulates routes by imitating expree.js
  • App.js: main entry
  • Conf-db.js Public mysql configuration
  • The controller handles data encapsulation for mysql
  • Db-mysql. js Specifies the package that mysql sends and accepts
  • Model-model.js returns a unified definition of parameters
  • Router-router. js Route processing encapsulation

  

package.json

"scripts": {
 "test": "echo \"Error: no test specified\" && exit 1",
"dev": "cross-env NODE_ENV=dev nodemon app.js" },
"dependencies": { 
  "mysql": "^2.18.1"
},  
"devDependencies": {
 "cross-env": "^7.0.3","nodemon": "^2.0.7"
}
Copy the code

Four: specific back-end logic implementation

module –  route.js

conf  db.js 

db – mysql.js 

model  – resModel.js

app.js 

controller  blog.js 

It’s kind of like the following, but everything else is pretty much the same

router –  blog.js 

It’s kind of like the following, but everything else is pretty much the same

Five: SQL injection, XSS, password encryption, log, etc

Sql injection

const escape = (value) => { return mysql.escape(value)}module.exports = { escape}; // Use the example username = escape(username)Copy the code

xss

npm install xss --save const xss = require('xss'); // Use the example username = escape(username)Copy the code

Password encryption

Encapsulate the public password encryption file cryptopwd.js

const crypto = require('crypto'); const PWD_KEY = 'QQWW123_161sdsad.. '; const crytoPwd = (pwd) => { const md5 = crypto.createHash('md5'); const pwdStr = `pwd=${pwd}&key=${PWD_KEY}`; const newpwd = md5.update(pwdStr).digest('hex'); return newpwd; }module.exports = crytoPwd; // use password = crytoPwd(password)Copy the code

The log

Package log.js processing, build logs folder under the.log file to collect information

// log.js const fs = require('fs'); const path = require('path'); const writeLog = (writeStream,log) => { writeStream.write(log+'\n'); }; const createWirteStream = (fileName) => { const fullName = path.join(__dirname,'.. / ', '.. /','logs',fileName) let writeStream = fs.createWriteStream(fullName, {flags: 'a', // continue to write}) return writeStream; }const accessWriteLog = (log) => { const accessStream = createWirteStream('access.log'); writeLog(accessStream,log); }module.exports = { accessWriteLog}; / / use / / to a log const logStr = ` ${the req. Method}, ${the req. Url}, ${the req. Headers [' the user-agent ']}, ${Date. Now ()} `; accessWriteLog(logStr);Copy the code

Parse the log, using Node’s readLine

Const fs = require('fs'); const path = require('path'); const readLine = require('readline'); const process = require('process'); const fileName = path.join(__dirname,'.. / ', '.. /','logs','access.log'); const fullName = fs.createReadStream(fileName); let rl = readLine.createInterface({ input: fullName})rl.on('line',(line) => { if(! line){ return } console.log(line); })rl.on('close',() => {console.log(" finished "); process.exit(0); Exit the current process})Copy the code

Six: Redis stores token and other user information

npm install redis --save
Copy the code

Encapsulate a Redis file, encapsulate get and set methods

Const redis_config = {port: 6379, host: '127.0.0.1'}; const redis = require('redis'); const { redis_config } = require(".. /conf/db")// connect const redisClient = redis.createclient (redis_config.port, redis_config.host)redisClient.on('error', (err) => { console.log(err)})const get = (key) => { return new Promise((resolve,reject) => { redisClient.get(key, (err, val) => { if(err){ reject(err); }; if(! val){ resolve(null) } try { resolve(JSON.parse(val)) } catch (error) { resolve(val) } }) })}; const set = (key, val) => { if (typeof val === 'object') { val = JSON.stringify(val); } redisClient.set(key, val, redis.print)}; module.exports = { get, set}Copy the code

Each time the interface is requested, check whether the token is correct and exists. If not, a user token store is produced

const getResult = await get(token); // set token part let token = req. Cookie ['token']; if (! token) { token = `${Date.now()}_${Math.random() * 100000}`; }; set(token, {})Copy the code

Seven: Problems encountered in writing at present

1: node handles post requests

If you look at most cases, it’s queryString, but when I do it, I return this:

My input

The results obtained

To solve

Req.on ('data', function (chunk) {req.body += chunk.tostring (); }); Req. on('end', function () {req.body = json.parse (req.body)})Copy the code

2: NPM mysql package failed to handle latest mysql version.

client does not support authentication protocol requested by server; 
consider upgrading mysql client
Copy the code

If the tutorial still does not resolve the problem, please check to see if your Node user permissions are ready. You need to set the user before modifying the protocol. If the protocol is set, you can modify the protocol directly.