Nodejs 有人做过node https发送post请求?错误提示unknown protocol:openssl\ssl\s23_clnt.c:766:

Nodejs 有人做过node https发送post请求?错误提示unknown protocol:openssl\ssl\s23_clnt.c:766:

D:\node\weishi>node post problem with request: 8820:error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:un known protocol:openssl\ssl\s23_clnt.c:766:

代码 var https = require(‘https’); var options = { hostname: ‘open.t.qq.com’, port: 80, path: ‘/api/auth/token’, method: ‘POST’ }; var req = https.request(options, function (response) { var str = ‘’; response.on(‘data’, function (data) { str = str + data; }); response.on(‘end’, function () { console.log(str); }); }); req.on(‘error’, function (e) { console.log('problem with request: ’ + e.message); }); //req.write(""); req.end();


3 回复

根据你提供的问题描述,你遇到的错误是因为在发送 HTTPS 请求时,端口设置为 80(HTTP 的端口),而不是 443(HTTPS 的默认端口)。同时,代码中使用了 https 模块,但没有正确配置 SSL/TLS 选项。下面是修改后的代码示例,以解决你的问题:

const https = require('https');

// 设置正确的主机名、端口和路径
const options = {
    hostname: 'open.t.qq.com',
    port: 443,
    path: '/api/auth/token',
    method: 'POST',
    headers: {
        'Content-Type': 'application/json'
    }
};

// 创建 HTTPS POST 请求
const req = https.request(options, (res) => {
    let data = '';

    // 接收数据片段
    res.on('data', (chunk) => {
        data += chunk;
    });

    // 数据接收完毕后处理
    res.on('end', () => {
        console.log(data);
    });
});

// 错误处理
req.on('error', (e) => {
    console.error(`问题出现在请求中: ${e.message}`);
});

// 发送请求体(如果需要的话)
const postData = JSON.stringify({
    key: 'value'
});

req.write(postData);

// 结束请求
req.end();

解释

  1. 端口设置:将 port 从 80 改为 443,因为我们要发送的是 HTTPS 请求。
  2. 请求体:如果你需要发送请求体,可以使用 JSON.stringify() 将其转换为字符串,并通过 req.write() 方法发送。
  3. 错误处理:req.on('error') 监听器用于捕获并处理请求过程中可能出现的任何错误。

这样修改后,你应该能够成功发送 HTTPS POST 请求,而不必担心 unknown protocol 错误。


https 默认端口是 443,你的 options 里用的是 80 端口,可能是这个?

根据你的描述,问题可能出在 options 对象中,特别是 port 和 hostname 的配置。当你使用 HTTPS 时,端口应该是 443 而不是 80。同时,你需要设置 agent 为 false 来避免潜在的代理问题。

以下是修正后的代码示例:

const https = require('https');

const options = {
  hostname: 'open.t.qq.com',
  port: 443,
  path: '/api/auth/token',
  method: 'POST',
  agent: false, // 确保不使用代理
};

const req = https.request(options, (res) => {
  let data = '';

  res.on('data', (chunk) => {
    data += chunk;
  });

  res.on('end', () => {
    console.log(data);
  });
});

req.on('error', (e) => {
  console.error(`问题出现在请求中: ${e.message}`);
});

// 发送 POST 数据
const postData = JSON.stringify({
  key: 'value'
});

req.write(postData);
req.end();

解释:

  • hostname 设置为目标服务器的域名。
  • port 设置为 443,因为 HTTPS 默认使用此端口。
  • agent: false 避免某些网络环境下的代理问题。
  • 使用 JSON.stringify 将 POST 数据转换为字符串,并通过 req.write() 方法发送数据。
  • 监听 data 和 end 事件来处理响应数据。
  • 错误处理通过监听 error 事件实现。

这样应该可以解决你的问题。

回到顶部