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

Flask服务无法接收Node.js发起的GET请求问题排查

Node.js发起GET请求被Flask拒绝连接,但curl可正常访问的问题

在PowerShell中通过node myfile.js运行JS文件时,Flask服务器无法接收其发起的GET请求,报错Error: connect ECONNREFUSED ::1:44444,但用curl访问同一http://localhost:44444/startup端点能正常返回200状态码及响应内容。

错误信息

Error: TypeError: fetch failed
    at Object.fetch (node:internal/deps/undici/undici:11457:11)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  cause: Error: connect ECONNREFUSED ::1:44444
      at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1494:16) {
    errno: -4078,
    code: 'ECONNREFUSED',
    syscall: 'connect',
    address: '::1',
    port: 44444
  }
}

Flask 代码

from flask import Flask, jsonify
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

@app.route('/startup', methods=['GET'])
def startup():
    response = {'message': 'Server has started!'}
    return jsonify(response), 200

if __name__ == '__main__':
    app.run(host='localhost', port=44444)

Node.js 代码

fetch('http://localhost:44444/startup', {
    method: 'GET',
    })
    .then(response => response.json())
    .then(data => console.log(data))
    .catch((error) => {
        console.error('Error:', error);
    });

curl 访问结果

curl http://localhost:44444/startup


StatusCode        : 200
StatusDescription : OK
Content           : {"message":"Server has started!"}

RawContent        : HTTP/1.1 200 OK
                    Access-Control-Allow-Origin: *
                    Connection: close
                    Content-Length: 34
                    Content-Type: application/json
                    Date: Tue, 11 Jul 2023 22:31:14 GMT
                    Server: Werkzeug/2.2.3 Python/3.11.2

                    {"m...
Forms             : {}
Headers           : {[Access-Control-Allow-Origin, *], [Connection, close], [Content-Length, 34], [Content-Type,
                    application/json]...}
Images            : {}
InputFields       : {}
Links             : {}
ParsedHtml        : mshtml.HTMLDocumentClass
RawContentLength  : 34

解决方案

问题核心是localhost的解析差异:

  • Windows PowerShell中的curl会将localhost解析为IPv4地址(127.0.0.1),而Node.js默认优先使用IPv6地址(::1)。
  • Flask通过host='localhost'启动时,部分系统配置下仅监听IPv4的127.0.0.1,未监听IPv6的::1,导致Node.js的IPv6连接被拒绝。

两种解决方式任选其一:

  1. 修改Flask代码,让服务器同时监听IPv4和IPv6地址:
    if __name__ == '__main__':
        app.run(host='::', port=44444)  # ::表示监听所有IPv4和IPv6地址
    
  2. 修改Node.js代码,直接指定IPv4地址访问:
    fetch('http://127.0.0.1:44444/startup', {
        method: 'GET',
    })
    // 后续代码保持不变
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 09:05:21