解决 npm install 报错 connect ECONNREFUSED 问题

使用 npm install 安装包一直报错 errno ECONNREFUSED,本文记录解决方案。

问题复现

在安装npm 任何包时都会报错:

代码语言:javascript
复制
$ npm install --save hexo-blog-encrypt
npm WARN config global `--global`, `--local` are deprecated. Use `--location=global` instead.
npm ERR! code ECONNREFUSED
npm ERR! syscall connect
npm ERR! errno ECONNREFUSED
npm ERR! FetchError: request to https://registry.npmmirror.com/hexo-blog-encrypt failed, reason: connect ECONNREFUSED 127.0.0.1:31181
npm ERR!     at ClientRequest.<anonymous> (E:\Program Files\nodejs\node_modules\npm\node_modules\minipass-fetch\lib\index.js:130:14)
npm ERR!     at ClientRequest.emit (node:events:527:28)
npm ERR!     at onerror (E:\Program Files\nodejs\node_modules\npm\node_modules\agent-base\dist\src\index.js:117:21)
npm ERR!     at callbackError (E:\Program Files\nodejs\node_modules\npm\node_modules\agent-base\dist\src\index.js:136:17)
npm ERR!     at processTicksAndRejections (node:internal/process/task_queues:96:5)
npm ERR!  FetchError: request to https://registry.npmmirror.com/hexo-blog-encrypt failed, reason: connect ECONNREFUSED 127.0.0.1:31181
npm ERR!     at ClientRequest.<anonymous> (E:\Program Files\nodejs\node_modules\npm\node_modules\minipass-fetch\lib\index.js:130:14)
npm ERR!     at ClientRequest.emit (node:events:527:28)
npm ERR!     at onerror (E:\Program Files\nodejs\node_modules\npm\node_modules\agent-base\dist\src\index.js:117:21)
npm ERR!     at callbackError (E:\Program Files\nodejs\node_modules\npm\node_modules\agent-base\dist\src\index.js:136:17)
npm ERR!     at processTicksAndRejections (node:internal/process/task_queues:96:5) {
npm ERR!   code: 'ECONNREFUSED',
npm ERR!   errno: 'ECONNREFUSED',
npm ERR!   syscall: 'connect',
npm ERR!   address: '127.0.0.1',
npm ERR!   port: 31181,
npm ERR!   type: 'system',
npm ERR!   requiredBy: '.'
npm ERR! }
npm ERR!
npm ERR! If you are behind a proxy, please make sure that the
npm ERR! 'proxy' config is set properly.  See: 'npm help config'

npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\Administrator\AppData\Local\npm-cache_logs\2023-04-11T05_46_04_410Z-debug-0.log

核心错误信息:

代码语言:javascript
复制
reason: connect ECONNREFUSED 127.0.0.1:31181

问题原因

一般来说是访问国外网站工具或者加速器开启了网络代理,修改了相关配置导致 npm连接本机 31181 端口安装包。

确定这个问题可以查看 npm 的代理配置:

代码语言:javascript
复制
$ npm config get https-proxy
http://127.0.0.1/

然后查看本地端口没有对应的服务开启 (Windows):

代码语言:javascript
复制
$ netstat -ano

此时基本可以确认就是代理导致的问题。

解决方案

清空相关代理,http-proxyproxy

代码语言:javascript
复制
npm config delete https-proxy
npm config delete proxy

查看配置代理结果

代码语言:javascript
复制
npm config get proxy
npm config get https-proxy

如果二者都返回 null 说明删除成功

此时修改镜像源才可能有用。

之后安装包就可以了

代码语言:javascript
复制
$ npm install --save hexo-blog-encrypt
npm WARN config global `--global`, `--local` are deprecated. Use `--location=global` instead.

added 1 package in 2s

1 package is looking for funding
run npm fund for details

参考资料

文章链接:
https://cloud.tencent.com/developer/article/2266262