node搭建代理服务器

152 阅读1分钟

一.创建一个server.js,copy下面的代理服务器,用终端输入node server.js,启动代理

const http = require("http");

const https = require("https"); // 如果要支持HTTPS代理,需要引入https模块

// 创建服务器

const server = http.createServer();

// 请求转发处理器

function forwardRequest(req, res, targetUrl) {

  const protocol = targetUrl.startsWith("https://") ? https : http;

  // 创建代理请求选项

  const options = new URL(targetUrl);

  options.method = req.method;

  options.headers = req.headers;

  // 发送代理请求

  let proxyReq = protocol.request(options, (proxyRes) => {

    // 将代理响应 headers 设置到原始响应上

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

    // 将代理响应体数据转发到原始响应

    proxyRes.pipe(res);

  });

  // 错误处理

  proxyReq.on("error", (err) => {

    console.error(Error in forwarding request: ${err});

    res.statusCode = 500;

    res.end("Proxy Error");

  });

  // 将原始请求的数据转发到代理请求

  req.pipe(proxyReq);

}

// 监听当前服务器请求,接受request处理函数

server.on("request", (req, res) => {

  // 根据URL决定是否进行代理或直接响应

  if (req.url == "/" || req.url == "/user") {

    res.end("hello world");

  } else if (req.url === "/proxy" && req.method === "GET") { // 假设我们只对 '/proxy' 路径做代理,且仅支持 GET 方法

    const targetUrl = "img-home.csdnimg.cn/data_json/t…"; // 替换为你要代理的实际目标URL

    forwardRequest(req, res, targetUrl);

  } else {

    res.statusCode = 404;

    res.end("Not Found");

  }

});

// 监听端口

server.listen(5501, () => {

  console.log("❌❌❌❌5501启动成功  ----->  ");

});

二.创建一个html,请求会被node监听代理,直接copy就能用,要保持请求和代理的端口一致,注意我用jq做的请求

1.这是代理的,直接copy请求即可 $.get("http://localhost:5501/proxy", function (res) {})

2.未做代理直接请求的 $.get("img-home.csdnimg.cn/data_json/t…", function (res) { })