1) What is the middle layer

  • Is front end – request – > nodejs request — — — — – > the back-end response — — — – > nodejs – data processing response — — — — — — — > the front end. Such a process, the advantage of this process is that when the business logic is too much, or the business requirements are constantly changing, the front end does not need to change the business logic as much, low coupling to the back end. The front end is display and render. The backend retrieves and stores data. The middle layer processes the data structures and returns them to the front end as renderable data structures.
  • Nodejs plays the role of the middle layer, that is, to do the corresponding processing or rendering of the page according to the different requests of the client. During the processing, the data can be simply processed by the underlying Java side for real data persistence or data update, or it can be retrieved from the underlying data for simple processing and returned to the client.
  • We usually divide the Web realm into client and server, namely the front end and the back end, which includes gateways, static resources, interfaces, caches, databases, and so on. The middle layer, on the other hand, is a layer removed from the back end to deal with the parts that are more closely connected with the client in business, such as page rendering (SSR), data aggregation, interface forwarding and so on.
  • In terms of SSR, rendering the page well on the server side can speed up the user’s first screen loading speed, avoid blank screen when requesting, and help the website to do SEO, his benefits are relatively easy to understand.

2) What the middle tier can do

  • Proxies: In a development environment, we can use proxies to solve the most common cross-domain problems; In an online environment, we can use proxies to forward requests to multiple servers.
  • Caching: Caching is actually a requirement closer to the front end. The user’s actions trigger data updates, and the node middle tier can handle some of the caching requirements directly.
  • Traffic limiting: The middle layer of node. Traffic limiting can be performed for interfaces or routes.
  • Logging: Compared to other server languages, Node middle layer logging makes it easier to locate problems (whether in the browser or server).
  • Monitoring: good at high concurrency request processing, monitoring is also a suitable option.
  • Authentication: Having an intermediate layer to authenticate is also the realization of a single responsibility.
  • Routing: The front end needs to master the permissions and logic of page routing.
  • Server-side rendering: Node middle tier solutions are more flexible, such as SSR, template straight out, using some JS libraries to do pre-rendering, etc.

3) Advantages of node forwarding API (Node middle tier)

  • In the Java middle tier | PHP data, processing front end in pairs more friendly format
  • This solves the cross-domain problem on the front end because server-side requests do not involve cross-domain, which is caused by the same origin policy of the browser
  • Multiple requests can be merged through the middle tier to reduce front-end requests

4) How to do request merge forwarding

  • Use express middleware Multifetch to batch consolidate requests
  • Use Express + HTTP-proxy-middleware to implement interface proxy forwarding

5) Do not use a third-party module to manually implement a NodeJS proxy server to achieve request merge forwarding

1. Implementation idea

  • To set up the HTTP server, use the createServer method of the HTTP module of Node
  • A request packet sent by a client contains a request line, request header, and request body
  • The request message is sent to the target server using the REQUEST method of the HTTP module

2. Implementation steps

  • Step 1: HTTP server setup
const http = require("http");
const server = http.createServer();
server.on('request'.(req,res) = >{
    res.end("hello world")
})
server.listen(3000.() = >{
    console.log("running");
})
Copy the code
  • Step 2: Receive the request packets sent by the client to the proxy server
const http = require("http");
const server = http.createServer();
server.on('request'.(req,res) = >{
    // Receive the data sent by the client through req's data event and end event
    // Use buffer.concat
    //
    let postbody = [];
    req.on("data".chunk= > {
        postbody.push(chunk);
    })
    req.on('end'.() = > {
        let postbodyBuffer = Buffer.concat(postbody);
        res.end(postbodyBuffer)
    })
})
server.listen(3000.() = >{
    console.log("running");
})
Copy the code

This step requires buffer processing in NodeJS as the main data is transferred from the client to the server. The process is to stuff all the chunks of received data into an array and then merge them together to restore the source data. The merge method requires buffer. concat, which does not use the plus sign because it implicitly converts buffers to strings, which is not safe.

  • Step 3: Use the REQUEST method of HTTP module to send the request message to the target server

    The second step has the data uploaded by the client, but the request header is missing, so in this step, the request header is constructed based on the requirements of the request sent by the client, and then sent

const http = require("http");
const server = http.createServer();

server.on("request".(req, res) = > {
    var{ connection, host, ... originHeaders } = req.headers;var options = {
        "method": req.method,
        // With the table to find a site to do the test, the agent site modified here
        "hostname": "www.nanjingmb.com"."port": "80"."path": req.url,
        "headers": { originHeaders }
    }
    // Receive the data sent by the client
    var p = new Promise((resolve,reject) = >{
        let postbody = [];
        req.on("data".chunk= > {
            postbody.push(chunk);
        })
        req.on('end'.() = > {
            let postbodyBuffer = Buffer.concat(postbody);
            resolve(postbodyBuffer)
        })
    });
    // Forwards the data, receives the data returned by the target server, and forwards it to the client
    p.then((postbodyBuffer) = >{
        let responsebody=[]
        var request = http.request(options, (response) = > {
            response.on('data'.(chunk) = > {
                responsebody.push(chunk)
            })
            response.on("end".() = >{ responsebodyBuffer = Buffer.concat(responsebody) res.end(responsebodyBuffer); })})// Pass the request body using the write method of request
        request.write(postbodyBuffer)
        // Use the end method to send the requestrequest.end(); })}); server.listen(3000.() = > {
    console.log("runnng");
})
Copy the code