当前位置:网站首页>[introduction to node basics] - node middle layer does interface forwarding to realize cross domain requests
[introduction to node basics] - node middle layer does interface forwarding to realize cross domain requests
2022-07-23 09:56:00 【Lily】
Preface :
cause , Took over an old project four years ago (2018 Year of ), The project is front and rear end separation , And it is used by the front end node Cross domain problems solved . One node The small white , In order to better understand the construction and online deployment of the project , Reluctantly set foot on node Learning journey of .(PS: Sure enough , Own technical debt , You have to pay it back by yourself ╮(╯▽╰)╭).
that , This article starts with the principle , Take a look at the basics , then , Then practice according to the data . that , Let's see ,node How does the middle tier merge and forward requests ?
One 、 First time to know node Middle layer
1.1 What is the middle layer
The middle layer is , front end – request –>node.js---- request ----> Back end ---- Respond to ---->node.js– Data processing – Respond to ----> front end . Such a process , The advantage of this process is when there is too much business logic , Or when business needs are constantly changing , The front end does not need to change the business logic too much , Low coupling with the backend . The front end shows 、 Rendering . The back end obtains and stores data . The middle tier handles data structures , Return to the front-end available renderable data structures .
nodejs It acts as an intermediate layer , That is to do the corresponding processing or render the page according to the different requests of the client , When processing, you can simply process the obtained data and hand it to the bottom java There is real data persistence or data update , It can also get data from the bottom layer, do simple processing and return it to the client .
Usually , We put web The field is divided into client and server , That is, front-end and back-end , The back end here includes the gateway , Static resources , Interface , cache , Database etc. . And the middle layer , Just pull out another layer at the back end , In terms of business, deal with the parts that are more closely connected with the client , For example, page rendering (SSR), Data aggregation , Interface forwarding, etc .
1.2 What the middle tier can do
- agent : In the development environment , We can use agents to , Solve the most common
Cross domainproblem ; Online environment , We can use agents ,Forward requests to multiple servers( scene : The back-end using java springboot Develop multiple microservices ( It's not used here sping cloud Eureka Do service management and API Coordinate ), For every service IP Agreement , Port inconsistency ); - cache : Caching is actually a requirement closer to the front end , The user's action triggers the update of data ,node? The middle tier can directly handle part of the cache requirements ;
- Current limiting :node Middle layer , Current limiting that can respond to interfaces or routes ;
- journal : Compared with other server languages ,node Logging of the middle tier , It can locate the problem more conveniently and quickly ( Is it on the browser side or the server side );
- monitor : Good at high concurrency request processing , Monitoring is also a suitable option ;
- authentication : There is an intermediate layer to authenticate , It is also the realization of a single responsibility ;
- route : The front end needs to master the permissions and logic of page routing ;
- Server rendering :node The middle tier solution is more flexible , such as SSR、 Formwork straight out 、 Use a few JS Library pre rendering and so on .
1.3 node forward API(node Middle layer ) The advantages of
- You can put java/php The data of , Deal with a more friendly format for the front end ;
- Sure
Solve the cross domain problem of the front end, Because the server-side request does not involve cross domain , Cross domain is caused by the same origin strategy of the browser ; - Multiple requests can be merged through the middle tier ,
Reduce front-end requests.
An abstract understanding :
To understand Node Why layer can realize cross domain , First of all, we need to understand a principle : The cross domain problem is caused by the security mechanism of the same origin policy of the browser , There is no cross domain problem between servers , This is not to say that there is no security mechanism between servers , It's just a call between servers, whether it's through http Visit or through rpc Calls are protocol level mechanisms , There is no limit to homology . This is the same. Node The essence of cross domain , We put static files and Node The middle layer is in the same domain , So the front-end resources and Node Layer communication is not affected by the same origin strategy , then , We go through Node The middle layer forwards the front-end resource request to the real request address , In the middle layer, the data returned by the request is transmitted to the front end , In this way, the serial operation of this domain and other domains is realized .
Two 、 Related instance operations
2.1 Instance of a : How to merge and forward requests
Use express middleware multifetch You can merge requests in batches
Use express+http-proxy-middleware Implement interface proxy
Do not use third-party modules , Manually implement a nodejs proxy server , Realize request merging and forwarding :
2.1.1 Realize the idea
build http The server , Use Node Of http Modular createServer Method ;
Receive the request sent by the client , Is the request message , The request message includes the request line 、 Request header 、 Request body ;
Send the request message to the target server , Use http Modular request Method .
2.1.2 Implementation steps
First step :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");
})
The second step : Receive the request message sent by the client to the proxy server
const http = require("http");
const server = http.createServer();
server.on("request",(req,res)=>{
// adopt req Of data Events and end Event receives data sent by the client
// And use Buffer.concat With the
//
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");
})
This step mainly refers to data transmission from client to server , stay nodejs You need to use buffer Let's deal with it . The process is to put all received data segments chunk Into an array , then , Merge them together to restore the source data . The merge method requires Buffer.concat, The plus sign cannot be used here , The plus sign will implicitly buffer Convert to string , This transformation is not safe .
The third step : Use http Modular request Method , Send the request message to the target server
The second step is to get the data uploaded by the client , But the request header is missing , So in this step , The request header needs to be constructed according to the request sent by the client , And then send
const http = require("http");
const server = http.createServer();
server.on("request", (req, res) => {
var {
connection, host, ...originHeaders } = req.headers;
var options = {
"method": req.method,
// I found a website to test with the table , The proxy website modifies here
"hostname": "www.nanjingmb.com",
"port": "80",
"path": req.url,
"headers": {
originHeaders }
}
// Receive data sent by 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)
})
});
// Forward the data , And receive the data returned by the target server , And then forward 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);
})
})
// Use request Of write Method to pass the request body
request.write(postbodyBuffer)
// Use end Method sends the request to
request.end();
})
});
server.listen(3000, () => {
console.log("runnng");
})
Last
Relevant examples found on the Internet are , code snippet , There is no complete project , I'm in a fog (PS: It may also be that my understanding and practical ability are too poor o(╥﹏╥)o). I searched a lot of information , Fortunately, I found two big guys' blogs (Keyon Y and jsliang), Keep filling the hole .KeyonY The bosses Node Intermediate practice , There are five articles in the whole series , You can learn more about , And with node Middle tier project , Open the box , finally , It meets my need to start Xiaobai .jsliang Of Node practice , yes from 0 From the foundation to the official website of the actual combat enterprise , From the beginning to the project online deployment , Probably tens of thousands of words , Including the back-end part , Very detailed and specific .
Reference blog :
3-10 Tell me what you understand node How does the m-server merge and forward requests ? https://www.cnblogs.com/ifon/p/15991399.html
Two simple Node.js Forwarding service implementation https://zhuanlan.zhihu.com/p/392845487
Use Nodejs Reverse proxy https://blog.51cto.com/u_12879490/1921947
nodejs Interface forward https://blog.51cto.com/xutongbao/5432318
Cross domain solutions Node Middle layer https://juejin.cn/post/6844903895030824974
node Middleware interface forwarding , From then on, there is no need to bother the back-end students with cross domain problems https://juejin.cn/post/6844904151042752525
边栏推荐
- 抖音白天与晚上触发不同特效的Graph节点编写
- J.Serval and Essay(tarjan求拓扑序)
- Hfish蜜罐的搭建与测试
- 分库分表真的适合你的系统吗?聊聊分库分表和NewSQL如何选择
- Peptide nucleic acid coupled polypeptide ile Glu Gly Arg PNA (s-2222) | BOC Leu Gly Arg PNA
- LeetCode 提供的main函数中 JsonArray 所使用的jar包
- 目前都有哪些年利率6%左右的保本理财产品?
- Tensorflow 2.0深度学习教程
- DNS and DHCP of network security foundation
- 重绘按钮,做个自己的圆形LED指示灯
猜你喜欢
随机推荐
insert引起的db file sequential read之改善
Canal Chapter 8
PNA PNA modified polypeptide bz- (DL) - Arg PNA | z-ala-ala-leu-pna | suc ala ala ala PNA
PNA PNA modified polypeptide Pro Phe Arg PNA (s-2302) | DNP Gly x l Pro Gly PNA
.split(“,“, -1) 和 .split(“,“) 的区别
Peptide nucleic acid (PNA) coupled with membrane penetrating peptides (CCPs) (KFF) 3K to form CCPs PNA | peptide nucleic acid
Spark 内存管理机制 新版
2022-07-22:以下go语言代码输出什么?A:1;B:1.5;C:编译错误;D:1.49。 package main import “fmt“ func main() { var i
MySQL数据库UDF提权学习
2022年了,软件测试这个行业还吃香么?
d类型不同的模板错误
Several important problems of port completion
CMake入门教程
分享两个好玩好看的特效
How to learn SCM based on zero?
567. 字符串的排列
Canal 03 (8 chapters in total)
Get the C language pointer in one article
第一次改开源中间件keycloak总个结
express操作mysql,sql哪里写错了?








![[secret history of bug] uint8 data exceeds the type range, output 0x0102](/img/b6/86e017ccee26fcdea8b653731fea91.png)
