如何通过Node.js https库的https.get调用本地HTTP端点并解决协议报错
报错根因
你把Node内置的https模块和明文HTTP地址混用了:
- Node的内置网络模块是严格按协议拆分的,
https模块只支持发起带TLS加密的HTTPS请求,根本不解析http://开头的明文地址 - 你传入的目标是本地跑在80端口、无SSL/TLS加密的HTTP服务,和
https.get的能力完全不匹配,自然会抛出「不支持协议http:,期望使用https:」的异常
修正操作
- 把代码里所有
https模块的调用换成http模块,对应匹配你本地的明文HTTP服务 - 在文件顶部补充
http模块的引入:- CommonJS 环境:写
const http = require('node:http') - TypeScript/ESM 环境:写
import http from 'node:http'
- CommonJS 环境:写
- 原有请求URL
http://localhost/events/recent本身没有问题,不需要修改
修正后可直接运行的代码
import http from 'node:http' // CommonJS环境请替换为 const http = require('node:http') var req = http.get(`http://localhost/events/recent`, (response) => { var responseCode; var responseBody = []; response.on("data", (data) => { responseBody.push(data); }); response.on("end", () => { // 原代码此处冗余传入了data参数,end事件本身不携带响应数据 var result = Buffer.concat(responseBody); responseCode = response.statusCode; if (response.statusCode === 200) { processResult(result); } else { console.log(`The Response failed with status code: ${responseCode}`); } }); }); req.end();
提醒:别反向踩坑——如果之后要请求带加密的HTTPS地址,再把模块换回
https即可,不管哪个方向混用模块和协议,都会触发同类报错。
内容的提问来源于stack exchange,提问作者benhorgen
相关产品推荐
相关产品推荐

