前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >使用代理ip来规避的做法用nodejs具体要怎么做?

使用代理ip来规避的做法用nodejs具体要怎么做?

作者头像
超级小可爱
发布2023-03-18 16:13:48
5050
发布2023-03-18 16:13:48
举报
文章被收录于专栏:小孟开发笔记小孟开发笔记

首先要说明一点,node-proxy-server 链接,适用于普通页面开发,配置简单,node 命令启动、支持跨域

接着我们往下看:

1.配置

配置接口地址的拦截,以及代理接口的地址。

 
   let conifg = {
 
   ‘/xxxx1’: { // 需要拦截的本地请求路径
 
   target: ‘http://xxxxxxxx.com’, // 代理地址
 
 
   port: 80, // 端口,默认80,某些地址可能是8080
 
  
   },
 
 
  ‘/xxxx2’: {
 
 
  target: ‘http://xxxxxxxx.com’,
 
  port: 80,
 
  }
 
   // …other path
  
  };

2.中间代理服务器

主要利用nodejs的 http 和 fs模块,创建一个中间服务器,接受页面请求,再通过中间服务器去请求真实接口,返回数据。

  let http = require(‘http’);

 
  let fs = require(‘fs’);
 
  // 创建中间代理层http服务
 

  let app = http.createServer(function (request, response) {
 

  // 主要逻辑:
 
  // 1.拦截请求配置的路径 if(hasProxy(url, request, response))
 
  // 2.普通请求,直接通过
 
  });

3.拦截请求,转发请求

根据配置中的设定的拦截路径,拦截请求,并且转发到真实地址中。

 // 判断是否存在代理地址
 
  function hasProxy(url, request, response) {
 
 
  for (const key in conifg) { // 如果存在多个拦截路径
 
  const { target, port } = conifg[key];
 
 
  let info = target.split(‘//’);
 
  let opts = { // 请求参数
 
  protocol: info[0],
 
 
  host: info[1],
 
  port: port || 80,
 
  method: request.method,
 

  path: url,
 
 
  json: true,

  headers: {}
 
  }
 
  proxy(opts, request, response);
 
  return true;
 
  }
 
  return false;
 
  }
 
  // 代理转发
 
  function proxy(opts, request, response) {
 
  // 请求真实代理接口
 
  var proxyRequest = http.request(opts, function (proxyResponse) {
 
  // 代理接口返回数据,写入本地response
 
  proxyResponse.on(‘data’, function (chunk) {
 
  response.write(chunk, ‘binary’);
 
  });
 
 
  // 代理接口结束,通知本地response结束
 
  proxyResponse.on(‘end’, function () {
 
  response.end();
 
  });
 
  response.writeHead(proxyResponse.statusCode, proxyResponse.headers);
 
 
  });
 
 
 
  // 本地接口数据传输,通知代理接口请求
 
 
  request.on(‘data’, function (chunk) {
 
 
  proxyRequest.write(chunk, ‘binary’);
 
  });
 
 
  // 本地请求结束,通知代理接口请求结束
 
  request.on(‘end’, function () {
 
  proxyRequest.end();
 
  });
 
  }

4.普通资源请求

非拦截请求,直接通过。

  
 // 普通请求和资源加载
 
  fs.readFile(__dirname + url, function (err, data) {
 
  if (err) {
 
  console.log(‘请求失败’, err);
 
  } else {
 
  response.end(data);

  }

  });

5.建议

爬虫目前的反扒机制,总的来说还是要让作业的时候,让自己看起来是个正常的用户访问,不然都白瞎

未经允许不得转载:肥猫博客 » 使用代理ip来规避的做法用nodejs具体要怎么做?

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1.配置
  • 2.中间代理服务器
  • 3.拦截请求,转发请求
  • 4.普通资源请求
  • 5.建议
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档