You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何在node-fetch中指定使用TLS v1.2版本

如何在node-fetch中指定使用TLS v1.2版本

嘿,我之前也碰到过一模一样的问题——用node-fetch请求时返回403 Forbidden,查了半天才发现是TLS版本不兼容的锅。其实解决起来很简单,因为node-fetch底层依赖Node.js的http/https模块,我们只需要通过自定义https.Agent来强制指定TLS v1.2版本就行,具体步骤如下:

1. 准备工作

确保你已经安装了node-fetch(v2和v3的写法略有区别,下面都会覆盖到):

# 安装v2版本(CommonJS)
npm install node-fetch@2

# 或者安装v3版本(ESM)
npm install node-fetch@3

2. 编写带指定TLS版本的请求代码

如果你用的是node-fetch v2(CommonJS):

const fetch = require('node-fetch');
const https = require('https');

// 创建强制使用TLS v1.2的Agent
const tls12Agent = new https.Agent({
  secureProtocol: 'TLSv1_2_method',
  // 注意:如果测试时遇到证书问题,可临时开启下面一行(生产环境绝对不要用!)
  // rejectUnauthorized: false
});

// 发起请求时传入这个Agent
async function fetchData() {
  try {
    const response = await fetch('https://你的目标接口地址.com', {
      agent: tls12Agent
    });
    
    if (!response.ok) {
      throw new Error(`请求失败:${response.status} ${response.statusText}`);
    }
    
    const result = await response.json(); // 根据需求换成.text()或.blob()
    console.log('请求结果:', result);
  } catch (err) {
    console.error('出错了:', err);
  }
}

fetchData();

如果你用的是node-fetch v3(ESM):

import fetch from 'node-fetch';
import https from 'https';

const tls12Agent = new https.Agent({
  secureProtocol: 'TLSv1_2_method'
});

async function fetchData() {
  try {
    const response = await fetch('https://你的目标接口地址.com', {
      agent: tls12Agent
    });
    
    if (!response.ok) {
      throw new Error(`请求失败:${response.status} ${response.statusText}`);
    }
    
    const result = await response.json();
    console.log('请求结果:', result);
  } catch (err) {
    console.error('出错了:', err);
  }
}

fetchData();

原理说明

Node.js的https.Agent负责管理HTTP/HTTPS请求的连接池,通过设置secureProtocol: 'TLSv1_2_method',我们强制要求所有通过这个Agent发起的请求都使用TLS v1.2协议,这样就解决了因为服务器不支持默认TLS版本而返回403的问题。

另外提个小建议:如果设置后还是403,可以检查下请求头是否符合服务器要求(比如有没有加合法的User-Agent),有些服务器会拦截看起来像爬虫的请求哦。

备注:内容来源于stack exchange,提问作者Dev01

火山引擎 最新活动