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

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

接着我们往下看:

1.配置

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

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

2.中间代理服务器

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

  1. let http = require(‘http’);
  2. let fs = require(‘fs’);
  3. // 创建中间代理层http服务
  4. let app = http.createServer(function (request, response) {
  5. // 主要逻辑:
  6. // 1.拦截请求配置的路径 if(hasProxy(url, request, response))
  7. // 2.普通请求,直接通过
  8. });

3.拦截请求,转发请求

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

  1. // 判断是否存在代理地址
  2. function hasProxy(url, request, response) {
  3. for (const key in conifg) { // 如果存在多个拦截路径
  4. const { target, port } = conifg[key];
  5. let info = target.split(‘//’);
  6. let opts = { // 请求参数
  7. protocol: info[0],
  8. host: info[1],
  9. port: port || 80,
  10. method: request.method,
  11. path: url,
  12. json: true,
  13. headers: {}
  14. }
  15. proxy(opts, request, response);
  16. return true;
  17. }
  18. return false;
  19. }
  20. // 代理转发
  21. function proxy(opts, request, response) {
  22. // 请求真实代理接口
  23. var proxyRequest = http.request(opts, function (proxyResponse) {
  24. // 代理接口返回数据,写入本地response
  25. proxyResponse.on(‘data’, function (chunk) {
  26. response.write(chunk, ‘binary’);
  27. });
  28. // 代理接口结束,通知本地response结束
  29. proxyResponse.on(‘end’, function () {
  30. response.end();
  31. });
  32. response.writeHead(proxyResponse.statusCode, proxyResponse.headers);
  33. });
  34. // 本地接口数据传输,通知代理接口请求
  35. request.on(‘data’, function (chunk) {
  36. proxyRequest.write(chunk, ‘binary’);
  37. });
  38. // 本地请求结束,通知代理接口请求结束
  39. request.on(‘end’, function () {
  40. proxyRequest.end();
  41. });
  42. }

4.普通资源请求

非拦截请求,直接通过。

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

5.建议

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

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

赞 (0)
分享到: 更多

评论 0