1.1 pre content
1.1.1 what is javascript
Concept: it follows ECMAScript standard, is the concrete implementation of ECMAScript, supports browser API,BOM and DOM, and supports node JS API
1.1.2 what is node js
Concept: javascript running environment based on chromev8 engine.
1.2Node.js download and install
Download from official website
1.3 configure npm global installation directory
You can find the path in the environment variable and enter the system variable
1.4 configuring system environment variables
2.0Node.js core API
2.1 document operation
Steps:
Step 1: introduce 'fs' module
code:
// Introducing fs module var fs = require(fs);
Step 2: operate API
Sample code
Synchronous write
var fs = require(fs); //Synchronous write let rel = fs.writeFileSync('./abc.txt','Hello') console.log(rel);
Asynchronous write
fs.writeFile('Lone brave.txt','Love you walking alone in the dark lane,Love the way you don't kneel',function (err,) { if (err) { return console.error('Output error',err); } console.log('Output complete'); });
Synchronous reading
let data = fs.readFileSync('./abc.txt') console.log(data.toString());
Asynchronous read
fs.readFile('./abc.txt',function(err,data){ console.log(data.toString()); })
Delete file
fs.unlink('./abc.txt',function(){ console.log('Deleted successfully') })
Create directory
fs.mkdir("./Small money",function(err){ if (err) { return console.error(err); } console.log("Directory created successfully."); });
Delete directory
fs.rmdir("./Small money",function(err){ if (err) { return console.error(err); } console.log("read /tmp catalogue"); });
Create recursive directory
fs.mkdir("./Loved ones/Lone brave",{recursive : true},function(err){ if (err) { return console.error(err); } console.log("Directory created successfully."); });
2.2 path operation
Sample code
Introduction path module
var path = require('path')
Returns the absolute path of the currently executed script
let url = path.resolve('dist') console.log(url);
Splice a path (! Plus _dirname is an absolute path, and not plus is a relative path.)
let url = path.join(__dirname,'a,b,c,d.txt') console.log(url);
2.3 node global object
1.__filename (file name of the currently executing script)
2.__dirname (directory of currently executing script)
3.setTimeout (the global function executes the specified function after the specified number of milliseconds)
4.clearTimeout (the global function is used to stop a timer previously created through setTimeout())
5.setInterval (the global function executes the specified function (cb) after the specified number of milliseconds (ms))
6.console
7.process (process is a global variable, that is, the attribute of the global object)
2.4 web module
var http = require('http') var fs = require('fs') var url = require('url') var querystring = require('querystring') var app = http.createServer(function(req,res){ //Use the url module to parse the route and parameter object of get request let path = url.parse(req.url,true) console.log(path.pathname); //Requested route console.log(path.query); //Request parameter object //Parsing post requests using querystring let postData = '' req.on('data', function(data){ postData += data }) req.on('end', function(){ //Parsed post request parameter object let body = querystring.parse(postData) }) /* Determine the requested page according to the route, and use fs to respond to the html page content */ // let url = req.url // let filePath = '.' // console.log(url); // if(url === '/' || url === '/index.html'){ // filePath += '/index.html' // }else if(url === '/job.html'){ // filePath += url // }else if(url === '/about.html'){ // filePath += url // }else{ // } // if(url === '/'){ // url = '/index.html' // } // if(url !== '/favicon.ico'){ // let data = fs.readFileSync(`.${url}`) // res.write(data.toString()) // } res.end() }) app.listen(9990)
3.0 express framework
3.1. Build an Express development environment
# To install express scaffold, this command does not need to be executed every time $ cnpm i express-generator -g # Create project $ express -e jd-server # Enter the project root directory $ cd jd-server # Dependency initialization $ cnpm i
In package JSON file, modify the startup command:
{ "scripts": { "start": "nodemon ./bin/www" } }
3.2 project directory structure
- public Static resource file management directory of the server - routes Routing management directory - views Web template file management directory - app.js Entry file - package.json NPM configuration file
3.3. Process of creating module
Taking the student module as an example, the creation steps are as follows:
Step 1: create a routing file
Create stu in the routes directory js, /routes/stu.js sample code:
var router = require('express').Router(); //Jump to the add student page router.get('/page/add', function(req,res){ //Render template res.render('stu_add') }) module.exports = router
Step 2: create a first level route
On app Register the primary route in the JS entry file, app JS sample code:
var express = require('express') //Import routing file var stuRouter = require('./routes/stu.js') var app = express() //Declare first level routing app.use('/stu', stuRouter)
Step 3: create a template file
Create stu in / views directory_ add. EJS file, / views/stu_add.ejs sample code:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>Add student</h1> <form action="/stu/add" method="POST"> <div> Student Name:<input type="text" name="stuname"> </div> <div> Student age:<input type="text" name="age"> </div> <div> <button type="submit">Submit</button> </div> </form> </body> </html>
Step 4: create a route to add student data
At / routes / stu JS file, / add secondary routes, / routes / stu JS sample code:
var router = require('express').Router(); router.get('/page/add', function(req,res){ res.render('stu_add') }) //Add the following code router.post('/add', function(req,res){ //Receive post request parameters let stu = req.body //Add database }) module.exports = router
4. Mongodb database
4.1. Install Mongodb and Mongodb Compass
slightly
4.2. Operate Mongodb in Node
4.2.1. Use mongoose
install
$ cnpm i mongoose --save $ cnpm i cors --save
4.2.2. Connect to database
For example, you can connect to the database in a route file in the express project, routes / index JS file, sample code:
var express = require('express'); var router = express.Router(); //1. Introduce mongoose var mongoose = require('mongoose') //2. Connect to the database mongoose.connect('mongodb://localhost:27017/blog',{ useNewUrlParser:true }).then(()=>{ console.log('Database connection succeeded'); }).catch(err=>{ console.log('Database connection failed'); }) //3. Create document model object var schema = new mongoose.Schema({ title: String, createTime: Number, author: String, content: String }) var Article = mongoose.model('articles',schema) //Query article router.get('/find', (req,res)=>{ //find(where) is a method to query multiple pieces of data. The parameters are query criteria Article.find().then(result=>{ //Query result array }) }) //Add article router.post('/add', (req,res)=>{ //create(obj) add method, and the parameter is the object to be added Article.create().then(result=>{ //result is the object successfully added }) }) module.exports = router;
API of document object (take Goods as an example):
//Add data. The create(g) parameter is the object to be added. After successful execution, the object to be added will be returned Goods.create(g).then(rel=>{}).catch(err=>{}) //When modifying data, updateOne() parameter 1 is the modification condition, and parameter 2 is the new object to be modified. The modified result object is returned when rel When n > 0, the modification is successful Goods.updatOne(where,params).then(rel=>{}).catch(err=>{}) //To delete data, the findOneAndDelete() parameter is the deletion condition and returns the object that was successfully deleted Goods.findOneAndDelete(where).then(rel=>{}).catch(err=>{}) //Query all, and the find() parameter is the query condition Goods.find(where).then(rel=>{}).catch(err=>{}) //Sort all queries. The sort() parameter is the sort condition, {price: 1} is the ascending order of price, {price: -1} is the descending order of price, and the multi condition syntax is {price:1, sal: -1} Goods.find().sort({price: -1,createTime: -1}).then(rel=>{}).catch(err=>{}) //Paged query, start indicates the starting position (index) of the query, and pageSize indicates the number of queries per page //start = (current page number - 1) × Number of entries per page Goods.find().skip(start).limit(pageSize).then(rel=>{}).catch(err=>{}) //Query the total number of records. The find() parameter is the query condition and returns the total number of current data //Total pages = math ceil(count/pageSize) Goods.find(where).count().then(rel=>{}).catch(err=>{}) Goods.find(where).countDocuments().then(rel=>{}).catch(err=>{}) //Fuzzy query, the query object is a conditional object containing regular expressions Goods.find({title: {$regex: /['pants']|['male']/}}).then(rel=>{}).catch(err=>{}) //In comparison query, $gt means greater than and $lt means less than in query criteria Goods.find({price: {$gt: 200, $lt: 300}}).then(rel=>{}).catch(err=>{}) //Self increasing Goods.updateOne({_id: goods._id}, {$inc: {see: 1}}).then(rel=>{}).catch(err=>{})
Here, take adding commodity classification as an example.
4.2.3 front end request
Use the asynchronous request method in jquery:
$.get(url, callback) $.post(url, params, callback)
Use Vue JS to realize page DOM rendering:
//Instantiate vue new Vue({ //option })
Vue options:
- el
- data
- methods
- created
- filters
- watch
Vue's instructions:
- v-text
- v-html
- v-if/v-else-if/v-else
- v-show
- v-for
- v-bind
- v-on
- v-model
Extension:
- layer pop-up plug-in
- layui front end framework
- wangEditor rich text editor
- Ecarts data visualization
4.3 implementation process of Node server module
4.3.1 core business logic encapsulation
Connect database
Create dB / index. In the root directory of the project JS file, code:
var mongoose = require('mongoose') function dbConnect(){ mongoose.connect('mongodb://localhost:27017/blog',{}).then(()=>{]}).catch(()=>{}) } module.export = dbConnect
On app JS entry file introduces and calls the method of connecting to the database:
var express = require('express') var dbConnect = require('./db/index.js') var app = express() dbConnect()
Encapsulate model objects
Taking the Article module Article as an example, create models / Article JS file, code:
var mongoose = require('mongoose') //Create rules for configuration objects var schema = new mongoose.Schema({ title: String, see: { //Number of views type: Number, default: 0 } }) //Create model objects var Article = mongoose.model('articles', schema) module.exports = Article
Put article JS in models / index JS, code:
module.exports = { Article: require('./Article.js') }
Use Article module in other files, code:
// routes/article.js file var Model = require('../models') Model.Article //Get Article model object
Encapsulate CRUD code
Create controller / index JS file, code:
/** * Method of adding data * @param {*} model Model object * @param {*} params Parameter object to add * @param {*} res Response object */ function add(model, params, res){ model.create(params).then(rel=>{ if(rel){ res.json({ code: 200, msg: 'Added successfully' }) }else{ res.json({ code: 300, msg: 'Add failed' }) } }).catch(err=>{ res.json({ code: 400, msg: 'Exception occurred while adding' }) }) } /** * Method of modifying data * @param {*} model Model object * @param {*} where modify condition * @param {*} params Modified object * @param {*} res Response object */ function update(model, where, params, res){ model.updateOne(where, params).then(rel=>{ if(rel.modifiedCount > 0){ res.json({ code: 200, msg: 'Modified successfully' }) }else{ res.json({ code: 300, msg: 'Modification failed' }) } }).catch(err=>{ res.json({ code: 400, msg: 'Exception during modification' }) }) } /** * Method of deleting data * @param {*} model Model object * @param {*} where Delete condition * @param {*} res Response object */ function remove(model, where, res){ model.findOneAndDelete(where).then(rel=>{ if(rel){ res.json({ code: 200, msg: 'Deleted successfully' }) }else{ res.json({ code: 300, msg: 'Delete failed' }) } }).catch(err=>{ res.json({ code: 400, msg: 'Exception while deleting' }) }) } /** * Paging query all data * @param {*} model Model object * @param {*} page Current page * @param {*} pageSize Number of entries per page * @param {*} where query criteria * @param {*} sort sort criteria * @param {*} res Response object */ async function find(model,page,pageSize,where,sort,res){ //Determine whether the page exists if(!page){ page = 1 }else{ page = parseInt(page) if(isNaN(page)){ //Judge whether it is a number page = 1 }else{ if(page < 1){ //Judge that the current page number cannot be less than 1 page = 1 } } } //Determine whether pageSize exists if(!pageSize){ pageSize = 10 }else{ pageSize = parseInt(pageSize) if(isNaN(pageSize)){ pageSize = 10 }else{ if(pageSize < 1){ pageSize = 3 }else if(pageSize > 100){ pageSize = 100 } } } //Total number var count = 0 await model.find(where).countDocuments().then(rel=>{ count = rel }) //Calculate total pages var totalPage = Math.ceil(count/pageSize) //Determine the maximum value of page if(totalPage > 0 && page > totalPage){ page = totalPage } //Calculation start position var start = (page - 1)*pageSize await model.find(where).sort(sort).skip(start).limit(pageSize).then(result=>{ if(result && result.length > 0){ res.json({ code: 200, msg: 'query was successful', data: result, page, pageSize, count, totalPage }) }else{ res.json({ code: 300, msg: 'No data found', data: [] }) } }).catch(err=>{ res.json({ code: 400, msg: 'Exception during query', data: [] }) }) } /** * Query all data without paging * @param {*} model Model object * @param {*} where query criteria * @param {*} sort sort criteria * @param {*} res Response object */ function query(model,where,sort,res){ model.find(where).sort(sort).then(rel=>{ if(rel && rel.length > 0){ res.json({ code: 200, msg: 'query was successful', data: rel, }) }else{ res.json({ code: 300, msg: 'No data found', data: [] }) } }).catch(err=>{ res.json({ code: 400, msg: 'Exception during query', data: [] }) }) } /** * Query a single piece of data * @param {*} model Model object * @param {*} where query criteria * @param {*} res Response object */ function findOne(model, where, res){ model.findOne(where).then(rel=>{ if(rel){ res.json({ code: 200, msg: 'query was successful', data: rel, }) }else{ res.json({ code: 300, msg: 'No data found', data: {} }) } }).catch(err=>{ res.json({ code: 400, msg: 'Exception during query', data: null }) }) } module.exports = { add, update, remove, find, findOne, query }
4.3.2 use of JWT
To install jsonwebtoken:
$ cnpm i jsonwebtoken --save
Generate token
Generally, a token will be generated in the logged in route, such as routes / user JS file:
var router = require('express').Router() var jwt = require('jsonwebtoken') //Administrator login router.post('/login',async function(req,res){ let u = req.body //Receive parameters //Database query. After the query is successful, a token is generated let user = {} // expiresIn validity period, in seconds let token = jwt.sign(user,'secret key',{expiresIn: 60 * 60 * 24 * 7}) res.json({ code: 200, token }) }) module.exports = router
Front end receiving token
login.html
<script> $.post('url', {}, function(res){ if(res.code === 200){ localStorage.token = res.token } }) </script>
Verify token
The front end sends the request and puts the token in the request header
<script> $.ajax({ url: '', headers: { token: localStorage.token } }) </script>
The token is verified on the server side and usually placed in the app JS middleware:
app.js code:
var express = require('express') var jwt = require('jsonwebtoken') var app = express() //Verification token (Middleware) //Configure routes without verification let pathRule = [ '/admin/user/login', '/user/reg', '/user/login', ] app.use(function(req,res,next){ if(pathRule.includes(req.path)){ next() return } //Get token var token = req.headers.token let result = null //Verify token jwt.verify(token,'secret key',function(err,data){ if(err){ switch(err.name){ case 'JsonWebTokenError': result = { errCode: 1, msg: 'invalid token' } break; case 'TokenExpiredError': result = { errCode: 2, msg: 'token be overdue' } break; } }else{ result = { errCode: 0, data: { username: data.username, role: data.role } } } }) if(result.errCode == 0){ next() }else{ res.json(result) } }) //route app.use('/user', xxx)