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

Ubuntu更新后ts-node仅能通过IP连接服务,localhost连接被拒求解

解决方案:Node.js http.request 连接localhost被拒问题

一、修复代码配置错误

你的代码中http.request的options配置存在核心错误:host字段不能包含http://前缀,该字段仅需填写主机名或IP地址。正确配置方式有两种:

方式1:拆分主机名和端口

var http = require('http');
var options = {
  hostname: 'localhost',
  port: 1337,
};

const callback = function(response) {
  var str = '';

  response.on('data', function (chunk) {
    str += chunk;
  });

  response.on('end', function () {
    console.log(str);
  });
}

http.request(options, callback).end();

方式2:直接传入完整URL

var http = require('http');
const targetUrl = 'http://localhost:1337';

const callback = function(response) {
  var str = '';

  response.on('data', function (chunk) {
    str += chunk;
  });

  response.on('end', function () {
    console.log(str);
  });
}

http.request(targetUrl, callback).end();

二、系统层面排查(Ubuntu更新后可能的解析问题)

若修复代码后仍出现连接被拒,大概率是Ubuntu更新后localhost的DNS解析优先级变化导致:

  1. 检查/etc/hosts配置
    打开/etc/hosts文件,确认存在127.0.0.1 localhost的映射。若存在::1 localhost(IPv6映射),可能导致Node优先尝试用IPv6连接,但你的服务绑定的是0.0.0.0(仅IPv4),此时可临时注释掉::1 localhost行测试。

  2. 强制Node使用IPv4连接
    可以通过两种方式强制Node优先使用IPv4:

    • 运行ts-node时添加环境变量:
      NODE_OPTIONS="--dns-result-order=ipv4first" ts-node your-file.ts
      
    • 在代码中指定IP协议版本:
      var http = require('http');
      var options = {
        hostname: 'localhost',
        port: 1337,
        family: 4, // 强制使用IPv4
      };
      
      const callback = function(response) {
        var str = '';
      
        response.on('data', function (chunk) {
          str += chunk;
        });
      
        response.on('end', function () {
          console.log(str);
        });
      }
      
      http.request(options, callback).end();
      

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 17:15:27