preface

I had written the front end and understood the back end but had not implemented the interface. Recently I am learning Node, so I built a simple background with Express to realize functions such as login and registration. After writing this Demo, I have deepened my understanding of the back end and understood the specific details of the template rendering of MVC mode without separation of the front and back ends.

This demo is a very simple comment system, users register after logging in to post comments, the page display comments. In fact, the scalability is still very high. The files used to store data at present can be changed to MongoDB or Mysql, and deletion and search functions can also be added. It can be a comment component of a forum or mall.

This article will talk about the implementation ideas and problems encountered in the process, let’s learn together. (Source at end of article)

rendering

Because the focus is on the back-end interface, the front-end style is simple

Project directory

I use express to build quickly generated, generated after the automatic import dependencies in app.js file

# installation express - the generator
$ npm install express-generator -g

Build the skeleton of the project quickly
$ express -e proName
Copy the code

Directory details

  • Public: static resources
    • Data. json —– Comment data and user data
    • Img, JS, CSS
  • Routes – routing
    • Index.js —– page route
    • Data.js —– Data interface routing
  • Views —– Page template
  • App.js —— project entry

Train of thought

We deploy the page on port localhost:3000, and the browser requests the page based on the page route in index.js. All data related operation interfaces of the page, such as user registration and Posting comments, are put in data.js, and the route is divided into page route and data route, so that the structure is clearer. View using EJS, rendering method for the following second, which is different from our usual HTML, EJS is JS template library, just like Java JSP. There are two ways to render data:

  • Just like in the previous text chat, you send the HTML directly to the client, and then get the data through Ajax for JS rendering
  • You import the data into the template and you render it on the back end and then you send the rendered HTML to the client in a way that used to be called front and back end separation.

The code on

The logic of the comment system is: users register and log in to post comments, which are displayed on the panel.

// app.js
// some code
app.use('/', index);  // Route with index.js when the request is localhost:3000/
app.use('/data', data);  // route data.js when the request is localhost:3000/data
// some code
Copy the code

Page routing

Redirect the page according to the route, res.render(page, data); Render the page template with data.

// index.js
var fs = require('fs');  // Import the module to be used
var express = require('express');
var router = express.Router();
var path = './public/data/';

/* Render home.ejs back to the browser */ when the request URL is localhost:3000
router.get('/'.function(req, res, next) {
  fs.readFile(path+'data.json', (err, data) => { // Read the file and execute the callback function
    if (err) {
      return res.send({
        status:0.info: 'fail..... '
      });
    }
    var obj = JSON.parse(data.toString());  // Return data
    return res.render('home', {  // Otherwise, if the read succeeds, render the template edit.jsp and return the data obj
      data: {
        arr: obj,
        name: req.cookies.username // The login user is stored in a cookie}}); }); }); router.get('/login'.function(req, res, next) {
  res.cookie('username'.' ');
  res.render('login'{}); }); router.get('/register'.function(req, res, next) {
  res.render('register'{}); }); router.get('/send'.function(req, res, next) {
  res.render('send', {
    data: {
      name: req.cookies.username
    }
  });
});

module.exports = router;
Copy the code

In our template we jump with the A tag, for example

<a href="/login">The login</a>--> Click to jump to the login interfaceCopy the code

Data routing

In the case of Posting a comment, an Ajax request is made when the user clicks the post button

// send.js
$.ajax({
            type: 'POST'.url: '/data/write'.dataType: 'json'.// The expected return type of the server
            data: obj,  // The comments sent by the user are transmitted as data
            success: function(data) {
                // some code
            },
            error: function() {
                alert('Failed to post comment, please try again! '); }});Copy the code

Corresponding background interface for receiving POST requests:

// data.js
/ /... some code
/* Post comments */
router.post('/write'.function(req, res, next) {
    if(! req.cookies.username) {// If the user is not logged in
        return res.send({
          status: 2.info: 'Please login first! '
        });
    }

  var obj = {
    username: req.cookies.username, 
    content: req.body.content
  };
  fs.readFile(path+'data.json', (err, data) => { // Read the file and execute the callback function
    if (err) {
      return res.send({
        status:0.info: 'Failed to read comment data'
      });
    }

    var arr = JSON.parse(data.toString());  // Get file data
    arr.splice(0.0, obj); // Insert new comment data
    var newData = JSON.stringify(arr);  / / to json

    // Add user comments to database (data.json), since I use file storage, later can be changed to MongoDB or mysql
    fs.writeFile(path+'data.json', newData, function(err){
        if(err){
            return res.send({
                status:0.info: 'Failed to add comment data'
            });
        }
        return res.send({
            status:1.info: obj
        });
    }); 
  });
});
// some code
Copy the code

Here’s a possible question:

  • The /data/write interface just stores the incoming data in a file. How does the new data render to home.ejs after the data.json data is updated? Json to the home.ejs template. When we post a comment, we write the new comment to data.json via the /data/write interface. If the comment is successfully written, we return data. Data. The status = 1. In the ajax success of send.js, we refresh the page when data.status=1. Home.ejs will naturally re-render.
  • One thing to say about template rendering: Every time the browser asks the server, in layman’s terms, every time the page is refreshed, the template is rerendered.

conclusion

  • This project adopts MVC, M is data (data.json and user.json), V (View) is EJS template, and C (route) is responsible for rendering template and data.
  • Source address: Windlany /express-comment, can fork down according to their own needs to change, feel good please give me a star.