How to do middle layer forwarding in nodejs

PHPz
Release: 2023-04-26 10:00:52
Original
758 people have browsed it

Node.js is a JavaScript runtime environment that allows developers to write server-side code using JavaScript language. During the development process, Node.js is often used as the middle layer to realize data transmission or forward requests between the front end and the back end. In this article, I will introduce in detail how to use Node.js for middle-tier forwarding.

1. Advantages of Node.js

As a JavaScript running environment based on event-driven and asynchronous I/O, Node.js has the following advantages in network application development:

  1. Asynchronous I/O model: Node.js adopts an event-driven model to asynchronousize I/O operations without blocking subsequent code execution, improving the system's throughput and concurrency performance.
  2. Single-threaded model: Node.js adopts a single-threaded model, which avoids the switching overhead between multiple threads and reduces the complexity of developers writing concurrent code.
  3. Lightweight: The core code of Node.js has only a few hundred files and very few library files, so it starts and runs quickly.
  4. Suitable for processing a large number of small data requests: Node.js is suitable for processing a large number of small data requests, such as WebSockets, long connections, HTTP polling, etc.

2. Node.js middle layer forwarding

  1. Client request transmission

Between the front end and the back end, the client Requests need to be forwarded through an intermediary layer. Users access the front-end page by using a browser, the front-end page sends a request to the middle tier, and the middle tier forwards the request to the back-end.

  1. Middle layer code implementation

The middle layer can be written using Node.js. The following are the code implementation steps:

(1) Create a Node HTTP server for .js.

const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  // 处理请求
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});
Copy after login

(2) Set the open port of the server and listen for HTTP requests on the specified port on the local machine.

(3) The middle layer receives the front-end request and forwards the request information to the back-end server.

const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  const options = {
    hostname: 'www.example.com',
    port: 80,
    path: req.url,
    method: req.method,
    headers: req.headers
  };

  const proxyReq = http.request(options, (proxyRes) => {
    proxyRes.on('data', (chunk) => {
      res.write(chunk);
    });

    proxyRes.on('end', () => {
      res.end();
    });

    res.writeHead(proxyRes.statusCode, proxyRes.headers);
  });

  req.on('data', (chunk) => {
    proxyReq.write(chunk);
  });

  req.on('end', () => {
    proxyReq.end();
  });
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});
Copy after login

(4) In the process of processing the request by the middle layer, copy the request information to a proxy request object, and add the address, port, request method and request header information of the back-end server to the proxy request object. , and then use the http.request() function to request the backend server.

(5) In the proxy request object, add a listening function to process the data and end events responded by the back-end server, and output the response data to the front-end.

(6) Set event monitoring in the middle layer at the same time, write the request data to the proxy request object when the front-end request data transmission is completed, and use the end function after the data writing is completed.

(7) After the processing is completed, release the proxy request object.

3. Summary

In this article, we introduced the method of Node.js as the middle layer to implement request forwarding. Through the excellent asynchronous I/O model and single-thread model, Node.js. js becomes a good tool for handling large amounts of small data requests. In practice, the middle layer forwarding implementation of Node.js is widely used in application fields. For example, in microservice architecture, Node.js is used to realize communication between services, which improves the reliability and scalability of the system.

The above is the detailed content of How to do middle layer forwarding in nodejs. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!