一般情况下,我们的node服务器,不会处理大型的数据,一般会作为
- 资源服务器,向客户端相应资源
- 代理服务器,用来转发客户端的请求,到真是的服务器
原理
- 拿到到客户端的请求头,封装为自己的头部,可以做一些额外的处理(如果客户端的请求路径和真是服务器请求路径有些许的差别,可以处理之后转发),向真实服务器发送请求
- 拿到真实服务器的响应头,作为自己的相应头,转发给客户端
demo,封装代理转发中间件
// /data/api/xxxxx ---> http://yuanjin.tech:5100/api/xxxx
const http = require("http");
module.exports = (req, res, next) => {
const context = "/data";
if (!req.path.startsWith(context)) { // 判断是否需要转发
//不需要代理
next();
return;
}
// 需要代理
const path = req.path.substr(context.length);
// 创建代理请求对象 request
console.log('req.headers', req.query)
const request = http.request(
{ // 根据客户端的请求体,封装自己的请求体,向真实服务器发送请求
host: "open.duyiedu.com",
path: path,
method: req.method,
headers: req.headers,
query: req.query,
},
(response) => {
// 根据真实服务器的响应体,封装相应体给客户端
res.status(response.statusCode);
for (const key in response.headers) {
res.setHeader(key, response.headers[key]);
}
response.pipe(res);// 把真实服务器的响应体,写入到代理相应体,转发给客户端
}
);
req.pipe(request); //把客户端请求体写入到代理请求对象的请求体中
};
中间件
- 安装
npm i http-proxy-middleware@1.0.3
- 使用
const { createProxyMiddleware } = require("http-proxy-middleware");
const context = "/data";
module.exports = createProxyMiddleware(context, {
target: "http://yuanjin.tech:5100",
pathRewrite: function (path, req) {
console.log(path.substr(context.length));
return path.substr(context.length);
},
});
- pathRewrite: 用来解决,客户端请求的路径,和代理请求真是的服务器的路径不一致的问题
中间件的其他配置,详细见官网https://github.com/chimurai/http-proxy-middleware