I used nodeJS as the middle layer in the project of Chuangyu before, but I didn’t understand the real reason behind it at that time. Later, in a conversation with an upperclassman, I learned that Ant Financial also uses a similar method, using NodeJS as an intermediate layer to request real background data. Later, when I went to Beijing, I saw that the current company was also moving towards the nodeJS backend. With the increase of knowledge, coupled with their own access to information, slowly summed up some principles.

From do micro channel small program caused by thinking

Recently, out of my hobby, I wrote a music player micro channel small program (originally wanted to use VUE to write, later because of the company’s business reasons, after the year may do micro channel small program, so I changed the front-end technology stack), the source on my GitHub: WX-Audio.

Consider: for performance and other reasons, the data format returned by the interface provided by the back-end may not be suitable for direct use by the front end. The sorting and filtering functions required by the front end, as well as the page presentation to the view layer, may require secondary processing of the data provided by the interface. This processing can be done on the front end, but it can be a waste of browser performance. For now, adding node ends is a good solution.

In the server code of my wechat small program Demo, I initiated HTTP requests to the real background (NetEase Cloud Music API) through HTTP module, and then built back-end services through Express module.

Initiate a request:

// http.js
var formatURL = require('./formatURL.js');
var http = require('http');
const POSThttp = function(request){
  return new Promise((resolve, reject) => {
    let body = '';
    // http模块拿到真实后台api的数据
    http.get(formatURL(request.body.musicname), function(res){
      res.on('data', (data) => {
        body += data;
      }).on('end', () => {
        // 格式化
        const {
          name,
          audio: musicUrl,
          page,
          album: {
            name: musicName,
            picUrl,
          },
          artists: [{
            name: singer,
          }],
        } = JSON.parse(body).result.songs[0];
        const reply = {
          name,
          picUrl,
          musicUrl,
          page,
          singer,
        };
        resolve(reply);
      });
    });
  });
};
module.exports = POSThttp;
Copy the code

Get the data back to the front end:

var express = require('express'); var POSThttp = require('./POSThttp.js'); var bodyParser = require('body-parser'); // Use body-parser to parse the post request parameters. If not, req.body is undefined. var app = express(); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.post('/', (req, res) => { POSThttp(req).then((data) => { res.send(data); }).catch((err) => { res.send(err); }); }); app.listen(3000, () => { console.log('open wx-audio server successful! ')});

These few lines of code make up a simple demo of the middle layer, formatting the parameters in the middle layer for easy use in the front end.

Why do we need an intermediate layer?

In fact, I think this question is similar to the common interview question: “Why do you need to separate the front and back ends?” The reasons can be summarized as follows:

There are problems with the website today

I had a conversation with a veteran with many years of work experience in Baidu about this kind of problem. When I mentioned the problem of sohu’s code redundancy and front-end coupling, he gave me the following answer and gave me the following suggestions:

In fact, it can be summarized that there are more or less such problems in the old projects of big companies (including the back-end rendering adopted by Baidu, Sohu and other companies) :

  • Front-end code is getting more complex
  • The front and back ends are still highly coupled
  • Not well supported across terminals

The solution proposed by our predecessors

Refer to the front and rear end separation solution of Taobao

  • As the front-end code became more and more complex, we wanted to reduce the amount of work possible and started using hierarchical structures like MV* to make front-end separation necessary.
  • The front end needs to handle more work and wants to be able to control the View, Router (e.g. SPA attempt)
  • The rise of various devices requires us to adapt pages to more places.

Start: The client-side MV* framework we tried, the back end exposes the data interface and processes the business logic, and the front end receives the data and processes the rendering logic.

About THE definition of MVC: MVC is a design pattern that divides an application into three parts: data (model), presentation layer (view), and user interaction (controller). In other words, an event occurs as follows: 1. The user interacts with the application. 2. The event handler of the controller is triggered. 3. The controller requests data from the model and gives it to the view. 4. The view presents data to the user. We can implement this MVC architectural pattern without using a class library or framework. The key is to divide each part of the MVC according to its responsibilities, separating the code cleanly into parts and maintaining good decoupling. This allows each part to be developed, tested, and maintained independently.

Backbone, EmberJS, KnockoutJS, AngularJS, etc.

But there are still problems with this approach:

The layers of responsibility overlap

  • Client-side Model is the processing of server-side Model
  • A client-side View is a different level from a server-side View
  • The client-side Controller and the Sever side Controller are separate
  • A client-side Route may not exist on the Server side

Performance issues

  • Rendering, values are done on the client side, there are performance issues
  • Need to wait for resources to complete to proceed, there will be a short white screen and flashing
  • The experience on low-speed networks on mobile devices is abysmal

Reuse problem

  • Templates cannot be reused, causing maintenance problems and inconsistencies
  • The logic cannot be reused, and the validation of the front end must be done again by the back end
  • Routes cannot be reused, and front-end routes may not exist on the back-end

Cross terminal problem

  • Services are too advanced, causing repeated implementation on different ends
  • The logic is too early, which makes maintenance difficult

Rendering is in the client side, template can not be reused, SEO implementation trouble

NodeJS as a full stack development solution for the middle tier

With NodeJS, the front end can focus more on the view layer and put more of the data logic in the Node layer.

We use the Node layer:

  • Forward data and connect services
  • Routing design, control logic
  • Render the page and optimize the experience
  • The performance issues introduced by the middle tier are balanced in the transition from asynchronous Ajax to synchronous rendering
  • More possibilities

More importantly, NodeJS is cheap to learn on the front end: we don’t have to learn a new language to do what developers used to do for us, and everything feels natural.

Technology is in constant change, only to keep up with the tide of technological innovation, in order not to be eliminated by The Times, whether people or enterprises.