You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js调用Yelp API出现connect ECONNREFUSED 127.0.0.1:443错误求助

问题原因分析

这个connect ECONNREFUSED 127.0.0.1:443错误的核心原因是你给https.get()传递的配置参数不正确,导致Node.js没有正确识别Yelp API的远程地址,反而尝试连接本地的443端口(也就是你自己的电脑)——而本地并没有在443端口运行HTTPS服务,所以连接直接被拒绝了。

具体来说,Node.js的https.get()方法有两种合法调用方式:

  1. 直接传入完整的URL字符串作为第一个参数,再跟回调函数
  2. 传入包含hostname、path、headers等字段的配置对象,再跟回调函数

你的代码用了第二种方式,但错误地把完整URL放在了配置对象的url属性里——这个属性并不是https.get()配置对象的合法字段。当Node.js找不到hostname字段时,就会默认用localhost作为目标地址,这就导致了连接本地443端口的错误。

修正后的代码方案

你有两种简单的修正方式,选一种就行:

方式一:直接传递URL字符串

把完整URL作为第一个参数传入,headers放在第二个参数的配置对象中:

const http = require('http');
const https = require('https'); // 建议把require放在文件顶部,避免重复加载

http.createServer(function (req, res) {
    const some_data = "name=your_business&city=your_city"; // 替换成实际查询参数
    const yelpMatch_url = encodeURI(`https://api.yelp.com/v3/businesses/matches/best?${some_data}`);
    const headers = {
        'Authorization': 'Bearer your_real_api_key' // 替换成你的Yelp API密钥
    };

    https.get(yelpMatch_url, { headers: headers }, function(response) {
        let body = '';
        response.on('data', function (chunk) {
            body += chunk;
        });
        response.on('end', function () {
            res.write(body);
            res.end();
        });
    }).on('error', function(e) {
        console.log(e.message);
    });
}).listen(3000); // 替换成你实际使用的端口号

方式二:正确拆分配置对象的hostname和path

如果更习惯用配置对象的方式,需要把URL拆分成hostname(域名)和path(接口路径+参数):

const http = require('http');
const https = require('https');

http.createServer(function (req, res) {
    const some_data = "name=your_business&city=your_city";
    const path = encodeURI(`/v3/businesses/matches/best?${some_data}`);
    const options = {
        hostname: 'api.yelp.com',
        path: path,
        headers: {
            'Authorization': 'Bearer your_real_api_key'
        }
    };

    https.get(options, function(response) {
        let body = '';
        response.on('data', function (chunk) {
            body += chunk;
        });
        response.on('end', function () {
            res.write(body);
            res.end();
        });
    }).on('error', function(e) {
        console.log(e.message);
    });
}).listen(3000);
额外提醒
  • 一定要把your_real_api_key替换成你从Yelp开发者平台获取的有效密钥,否则请求还是会失败
  • some_data需要是符合Yelp API要求的查询参数格式(比如name=xxx&city=xxx这样的键值对)
  • 尽量把require语句放在文件顶部,不要每次收到客户端请求时都重新加载模块,这样代码更高效

内容的提问来源于stack exchange,提问作者Jing Han

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:45:02