Study the Node – 04 – Express

Express installation

npm install express --save
Copy the code

Basic Cognition of Express

Hello World

/ / 1. Introduction
const express = require('express');

// 2. Create server application
// Http.createserver
const app = express()

// Expose the specified directory
// Once this is done, all resources in the public directory can be accessed directly through /public/ XXX
app.use('/public/', express.static('./public/'));

// When the server receives a get request /, the callback function is executed
app.get('/'.function(request, response) {
  response.send('hello express');
})

app.get('/about'.function(request, response) {
  response.send('This is about');
})

app.listen(3000.function() {
  console.log('app is running at port 3000.')});Copy the code

Automatically restart after modifying the code –nodemon

The installation

npm install -g nodemon
Copy the code

use

// Run the nodemon command to replace the node command nodemon app.jsCopy the code

Static Resource service

// Expose the specified directory
// Once this is done, all resources in the public directory can be accessed directly through /public/ XXX
// Go to the./public/ directory to find the corresponding resource
// Recommended
app.use('/public/', express.static('./public/'));

// When the first argument is omitted, it can be accessed by omitting /public
app.use(express.static('./public/'));
Copy the code

Art-template is used in Express

website

The installation

npm install --save art-template
npm install --save express-art-template
Copy the code

configuration

// Configure the art-template template engine
// The first parameter indicates that the art-template template engine is used when rendering files ending in.art
// Express-art-template is used to integrate art-template into Express
app.engine('art'.require('express-art-template'));


// Express provides a method for the response corresponding object: render
The render method is disabled by default, but can be used if a template engine is configured
// res.render(' HTML template name ', {template data})
// The first parameter cannot be written to the path. By default, the template file will be found in the views directory of the project
// Express has a convention that the developer will place all view files in the views directory
app.get('/'.function (req, res) {
  res.render('index.art', {
    user: {
      name: 'aui'.tags: ['art'.'template'.'nodejs']}}); });Copy the code

use

const express = require('express');

const app = express();
app.use('/public/', express.static('./public/'));

// Configure the art-template template engine
// The first parameter indicates that the art-template template engine is used when rendering files ending in.art
// Express-art-template is used to integrate art-template into Express
app.engine('html'.require('express-art-template'));

// If you want to change the default views directory, you can:
// app.set('views', default path of render function);


// Express provides a method for the response corresponding object: render
The render method is disabled by default, but can be used if a template engine is configured
// res.render(' HTML template name ', {template data})
// The first parameter cannot be written to the path. By default, the template file will be found in the views directory of the project
// Express has a convention that the developer will place all view files in the views directory
app.get('/'.function (req, res) {
  res.render('index.html');
});

app.get('/admin'.function(req, res) {
  res.render('admin/index.html', {
    title: 'express'
  });
});

app.listen(3000.function() {
  console.log('port 3000');
})
Copy the code

case

const express = require('express');

const app = express();
app.use('/public/', express.static('./public/'));
app.engine('html'.require('express-art-template'));

const comments = [
  {
    name: 'Joe'.message: 'It's a nice day! '.dateTime: '2015-10-16'
  },
  {
    name: 'Joe 2'.message: 'It's a nice day! '.dateTime: '2015-10-16'
  },
  {
    name: "Zhang SAN 3 '.message: 'It's a nice day! '.dateTime: '2015-10-16'
  },
  {
    name: 'Joe 4'.message: 'It's a nice day! '.dateTime: '2015-10-16'
  },
  {
    name: "Zhang SAN 5 '.message: 'It's a nice day! '.dateTime: '2015-10-16'}]// route
app.get('/'.function (req, res) {
  res.render('index.html', {
    comments: comments
  });
});

app.get('/post'.function(req, res) {
  res.render('post.html');
});

app.get('/pinglun'.function(req, res) {
  // Get the parameters of the get request
  const comment = req.query;
  comment.dateTime = '2021-07-28 00:00:00';
  comments.unshift(comment);
  res.redirect('/');
});


app.listen(3000.function() {
  console.log('port 3000');
})
Copy the code

Handling POST requests

Third-party middleware body-Parser is required

The installation

npm install --save body-parser
Copy the code

configuration

const bodyParser = require('body-parser')

/ / configuration of the body - parser
// Once this configuration is added, there will be an additional property on the REQ request object: body
// You can get the form POST request data directly from req.body
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
Copy the code

use

app.post('/post'.function(req, res) {
  console.log(req.body);
  const comment = req.body;
  comment.dateTime = '2021-07-28 00:00:00';
  comments.unshift(comment);
  res.redirect('/');
})
Copy the code

CRUD case

app.js

const express = require('express');
const router = require('./router');
const bodyParser = require('body-parser')

const app = express();
app.engine('html'.require('express-art-template'));

app.use('/public/', express.static('./public/'));
app.use('/node_modules/', express.static('./node_modules/'));

// It must be configured before mounting the route
/ / configuration of the body - parser
// Once this configuration is added, there will be an additional property on the REQ request object: body
// You can get the form POST request data directly from req.body
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
// router(app);
app.use(router);


app.listen(3000.function () {
	console.log('running 3000');
})

Copy the code

router.js

const fs = require('fs');
const students = require('./students.js');

// This is also inconvenient
// module.exports = function (app) {
// app.get('/', function (req, res) {
// fs.readFile('./db.json', 'utf8', function (err, data) {
// if (err) {
// return res.status(500).send('Server error.');
/ /}
// res.render('index.html', {
// students: JSON.parse(data).students
/ /});
/ /})
/ /})
// }

const express = require('express');

1. Create a routing container
const router = express.Router();

// 2. Mount all routes to the route container

/ / the main interface
router.get('/students'.function (req, res) {
  students.findAll(function (err, data) {
    if (err) {
      return res.status(500).send('Server error');
    }
    res.render('index.html', {
      students: data
    })
  })

})

// Add a page
router.get('/students/new'.function (req, res) {
  res.render('new.html');
})

// Click add
router.post('/students/new'.function (req, res) {
  const data = req.body;
  students.save(data, function (err, data) {
    if (err) {
      return res.status(500).send('Server error');
    }
    res.redirect('/students');
  });

})

// Edit the page
router.get('/students/edit'.function (req, res) {
  const id = parseInt(req.query.id);
  students.findById(id, function (err, data) {
    if (err) {
      return res.status(500).send('Server error');
    }
    res.render('edit.html', {
      student: data
    })
  })
})

// Click edit
router.post('/students/edit'.function (req, res) {
  const data = req.body;
  students.updateById(data, function (err, data) {
    if (err) {
      return res.status(500).send('Server error');
    }
    res.redirect('/students'); })})// Click delete
router.get('/students/delete'.function (req, res) {
  const id = parseInt(req.query.id);

  students.delete(id, function(err, data) {
    if (err) {
      return res.status(500).send('Server error');
    }
    res.redirect('/students');
  });
})

module.exports = router;

Copy the code

students.js

// Data manipulation file module
// Do not care about business

const fs = require('fs');
const dbPath = './db.json';

// Get a list of all students
// Callback is defined at the top and called at the bottom
exports.findAll = function (callback) {
	fs.readFile(dbPath, 'utf8'.function (err, data) {
		if (err) {
			return callback(err);
		}
		callback(null.JSON.parse(data).students); })}// Query students by ID
exports.findById = function (id, callback) {
	fs.readFile(dbPath, 'utf8'.function (err, data) {
		if (err) {
			return callback(err);
		}
		const students = JSON.parse(data).students;
		const student = students.find(item= > {
			return item.id == id;
		})
		callback(null, student); })}// Add save student
exports.save = function (student, callback) {
	fs.readFile(dbPath, 'utf8'.function (err, data) {
		if (err) {
			return callback(err);
		}
		const students = JSON.parse(data).students;
		student.id = students[students.length - 1].id + 1;
		students.push(student);
		const fileData = JSON.stringify({
			students: students
		});
		fs.writeFile(dbPath, fileData, function (err) {
			if (err) {
				return callback(err);
			}
			callback(null); }); })}// Update students
exports.updateById = function (student, callback) {
	fs.readFile(dbPath, 'utf8'.function (err, data) {
		if (err) {
			return callback(err);
		}
		const students = JSON.parse(data).students;
		const curStudent = students.find(item= > {
			return item.id == student.id;
		});
		for (let key in student) {
			curStudent[key] = student[key];
		}
		const fileData = JSON.stringify({
			students: students
		})
		fs.writeFile(dbPath, fileData, function (err) {
			if (err) {
				return callback(err);
			}
			callback(null); }); })}// Delete student
exports.delete = function (id, callback) {
	fs.readFile(dbPath, 'utf8'.function (err, data) {
		if (err) {
			return callback(err);
		}
		const students = JSON.parse(data).students;
		const studentIndex = students.findIndex(item= > {
			return item.id == id;
		})
		if(studentIndex ! = = -1) { students.splice(studentIndex, 1)}const fileData = JSON.stringify({
			students: students
		})
		fs.writeFile(dbPath, fileData, function (err) {
			if (err) {
				return callback(err);
			}
			callback(null); }); })}Copy the code