The installation

npm install body-parser -S
npm install express --save
npm install mysql -S
npm install express-jwt -S
npm install jsonwebtoken -S

Copy the code

Simple services

Create an empty project and NPM init-y loads the package.json file. Create app.js under the project and start the service:

const express = require('express') const bodyParser = require('body-parser') const expressJwt = require('express-jwt') const token = require('./jwt') const userDao = require('./userDao') const loginrecordDao = require('./loginrecordDao') Const app = Express () // Parse post body app. Use (bodyParser. Urlencoded ({extended: coded) False})) app.use(bodyParser.json()) // Enable CORS cross-domain app.all('*',function (req, res, next) { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild'); res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS'); if (req.method == 'OPTIONS') { res.send(200); /} else {next(); }}); Get ('/hello',function(req, res){res.send('hello')}) next) { res.status(404).send('Not found! Use (function (err, req, res, next) { console.error(err.stack) res.status(500).send('Something broke! ')}) app.listen(5000, function(){console.log('127.0.0.1:5000 running ')})Copy the code

Node. / app. Run js, visit http://127.0.0.1:5000/hello, there are data successfully

Connect the Mysql

Create table

CREATE TABLE `user` (
  `userid` varchar(40) NOT NULL,
  `username` varchar(255) DEFAULT NULL,
  `email` varchar(255) DEFAULT NULL,
  `password` varchar(255) DEFAULT NULL,
  `createtime` datetime DEFAULT NULL,
  `updatetime` datetime DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Copy the code

The connection

Create mysqlconnect. Js

var mysql   = require('mysql');
var connection = mysql.createConnection({
  host     : 'localhost', 
  user     : 'root',
  password : '123456.',
  database : 'vvweb'
});
 
connection.connect();

module.exports = connection
Copy the code

Then add a few data tests.

Operational data

Create userDao. Js

const mysqlConnection = require('./mysqlconnect') const onSelectOnlyUser = function(params){ return new Promise(function(resolve, reject){ let selectSql = 'SELECT userid,username,email,DATE_FORMAT(createtime,\'%Y-%m-%d %h:%i:%s\') AS createtime FROM user WHERE email = ? AND password = ? '; let selectSqlParams = [params.email, params.password]; / / update mysqlConnection. Query (selectSql selectSqlParams, function (err, result) { if(err){ console.log('[INSERT ERROR] - ',err.message); reject(err) return; } console.log('--------------------------SELECT----------------------------'); //console.log('INSERT ID:',result.insertId); console.log('SELECT ID:',result); console.log('-----------------------------------------------------------------\n\n'); resolve(result) }); }) } module.exports ={ onSelectOnlyUser }Copy the code

test

const userDao = require('./userDao')
 userDao.onSelectOnlyUser({ email : '111' , password: '123456' }).then((result)=>{
       console.log('-------- onSelectOnlyUser----', result)
    }).catch(err=>{
        console.log('-------- onSelectOnlyUser----', err)
    })
Copy the code

The use of JWT

Operation method

Create JWT. Js

const jwt = require('jsonwebtoken'); Const Token = {// generate encrypt:function(data,time){// encrypt data, Return jwt.sign(data, 'wtechtec', {expiresIn: Time})}, // decrypt:function(token){try {let data = jwt.verify(token, 'token'); return { token:true }; } catch (e) { return { token:false, data:e } } } } module.exports = Token;Copy the code

use

  const token = require('./jwt')
   let authorization =  token.encrypt( {data:rel.userid }, 60 * 30)
   console.log('-------- authorization ----', authorization )
Copy the code

Data indicates success

Integrated login Authorization

Create appfinally. Js

const express = require('express') const bodyParser = require('body-parser') const expressJwt = require('express-jwt') const token = require('./jwt') const userDao = require('./userDao') const loginrecordDao = require('./loginrecordDao') const app = express() // parse application/x-www-form-urlencoded app.use(bodyParser.urlencoded({ extended: false })) // parse application/json app.use(bodyParser.json()) app.all('*',function (req, res, next) { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild'); res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS'); if (req.method == 'OPTIONS') { res.send(200); /} else {next(); }}); App. Use (expressJwt({secret: 'token', // PublicKey algorithms: ['HS256']}). Unless ({path: ['/signIn', '] // specify path without Token resolution})) // Create an interface to debug app.get('/hello',function(req, res){ res.send('hello') }) app.post('/signIn', function(req, res){ userDao.onSelectOnlyUser(req.body).then((result)=>{ if (result.length === 0 || result.length >= 2) { res.status(201).send(result) } else { console.log('-------- signIn ----') let rel = result[0] let authorization = token.encrypt( {data:rel.userid }) rel['authorization'] = authorization console.log(rel) } }).catch(err=>{ res.send(err)  }) }) app.use(function ( req, res, next) { res.status(404).send('Not found! ') }) app.use(function (err, req, res, Next) {if (err. Name === 'UnauthorizedError') {res.status(401). Send ('token expired ') return}}) app.use(function (err, req, res, next) { console.error(err.stack) res.status(500).send('Something broke! ')}) app.listen(5000, function(){console.log('127.0.0.1:5000 running ')})Copy the code

note

App. Use (expressJwt({secret: 'token', // PublicKey algorithms: ['HS256']}). Unless ({path: ['/signIn', '] // Specify path without Token resolution}))Copy the code

Secret must have the same parameter as the second parameter in jwt.js, otherwise the token is invalid

Encrypt :function(data,time){// Data encrypt data,time expiration time 60 * 30 (30分) return jwt.sign(data, 'token', {expiresIn: time }) },Copy the code