一般情况下,我们的node服务器,不会处理大型的数据,一般会作为

  1. 资源服务器,向客户端相应资源
  2. 代理服务器,用来转发客户端的请求,到真是的服务器

原理

  1. 拿到到客户端的请求头,封装为自己的头部,可以做一些额外的处理(如果客户端的请求路径和真是服务器请求路径有些许的差别,可以处理之后转发),向真实服务器发送请求
  2. 拿到真实服务器的响应头,作为自己的相应头,转发给客户端

demo,封装代理转发中间件

  1. // /data/api/xxxxx ---> http://yuanjin.tech:5100/api/xxxx
  2. const http = require("http");
  3. module.exports = (req, res, next) => {
  4. const context = "/data";
  5. if (!req.path.startsWith(context)) { // 判断是否需要转发
  6. //不需要代理
  7. next();
  8. return;
  9. }
  10. // 需要代理
  11. const path = req.path.substr(context.length);
  12. // 创建代理请求对象 request
  13. console.log('req.headers', req.query)
  14. const request = http.request(
  15. { // 根据客户端的请求体,封装自己的请求体,向真实服务器发送请求
  16. host: "open.duyiedu.com",
  17. path: path,
  18. method: req.method,
  19. headers: req.headers,
  20. query: req.query,
  21. },
  22. (response) => {
  23. // 根据真实服务器的响应体,封装相应体给客户端
  24. res.status(response.statusCode);
  25. for (const key in response.headers) {
  26. res.setHeader(key, response.headers[key]);
  27. }
  28. response.pipe(res);// 把真实服务器的响应体,写入到代理相应体,转发给客户端
  29. }
  30. );
  31. req.pipe(request); //把客户端请求体写入到代理请求对象的请求体中
  32. };

中间件

  1. 安装

npm i http-proxy-middleware@1.0.3

  1. 使用
  1. const { createProxyMiddleware } = require("http-proxy-middleware");
  2. const context = "/data";
  3. module.exports = createProxyMiddleware(context, {
  4. target: "http://yuanjin.tech:5100",
  5. pathRewrite: function (path, req) {
  6. console.log(path.substr(context.length));
  7. return path.substr(context.length);
  8. },
  9. });