Node.js / Axios 不会连接到 localhost
Posted
技术标签:
【中文标题】Node.js / Axios 不会连接到 localhost【英文标题】:Node.js / Axios won't connect to localhost 【发布时间】:2018-09-06 19:48:53 【问题描述】:我有一个加密货币 (Nano) 节点在我的计算机上本地运行。它有一个 RPC API,我已经测试过我可以使用 curl 成功调用它。例如
curl -d ' "action": "account_balance", "account": "xrb_1aaprwcu9fac1tw3wesud5txb1zuiroti5xfr19bwozitjnnmbcbwpr1w95f" ' localhost:7076
但是我试图在节点脚本中做同样的事情并不断收到ECONNREFUSED
这是我的节点脚本(重要部分)。
const axios = require('axios')
const config = require('./config')
const rpc = axios.create(
baseURL: 'localhost:7076', // I've also tried 'http://localhost:7076'
// I've tried with and without proxy settings, I don't understand proxies very well though
/*proxy:
host: '127.0.0.1',
port: 7077
*/
)
function createAddress(accountIndex)
// Ensure accountIndex is a string
accountIndex = accountIndex + ''
// Get a new private key
return rpc.post('/',
action: 'deterministic_key',
index: accountIndex,
seed: config.walletSeed
)
// Add to the local wallet
.then(function(result)
return rpc.post('/',
action: 'wallet_add',
key: result.private,
wallet: config.walletId
)
)
// Return the account address
.then(function(result)
return result.account
)
.catch(function(err)
console.log('Error', err)
)
createAddress(52).then(function(address)
console.log(address)
)
这是错误。
Error Error: connect ECONNREFUSED 127.0.0.1:7076
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1170:14)
errno: 'ECONNREFUSED',
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 7076,
config:
adapter: [Function: httpAdapter],
transformRequest: '0': [Function: transformRequest] ,
transformResponse: '0': [Function: transformResponse] ,
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
validateStatus: [Function: validateStatus],
headers:
Accept: 'application/json, text/plain, */*',
'Content-Type': 'application/json;charset=utf-8',
'User-Agent': 'axios/0.18.0',
'Content-Length': 117 ,
method: 'post',
baseURL: 'http://localhost:7076',
url: 'http://localhost:7076/',
data: '"action":"deterministic_key","index":"52","seed":"***"' ,
request:
Writable
_writableState:
WritableState
objectMode: false,
highWaterMark: 16384,
finalCalled: false,
needDrain: false,
ending: false,
ended: false,
finished: false,
destroyed: false,
decodeStrings: true,
defaultEncoding: 'utf8',
length: 0,
writing: false,
corked: 0,
sync: true,
bufferProcessing: false,
onwrite: [Function: bound onwrite],
writecb: null,
writelen: 0,
bufferedRequest: null,
lastBufferedRequest: null,
pendingcb: 0,
prefinished: false,
errorEmitted: false,
bufferedRequestCount: 0,
corkedRequestsFree: [Object] ,
writable: true,
_events:
response: [Function: handleResponse],
error: [Function: handleRequestError] ,
_eventsCount: 2,
_maxListeners: undefined,
_options:
protocol: 'http:',
maxRedirects: 21,
maxBodyLength: 10485760,
path: '/',
method: 'post',
headers: [Object],
agent: undefined,
auth: undefined,
hostname: 'localhost',
port: '7076',
nativeProtocols: [Object],
pathname: '/' ,
_redirectCount: 0,
_requestBodyLength: 117,
_requestBodyBuffers: [ [Object] ],
_onNativeResponse: [Function],
_currentRequest:
ClientRequest
_events: [Object],
_eventsCount: 6,
_maxListeners: undefined,
output: [],
outputEncodings: [],
outputCallbacks: [],
outputSize: 0,
writable: true,
_last: true,
upgrading: false,
chunkedEncoding: false,
shouldKeepAlive: false,
useChunkedEncodingByDefault: true,
sendDate: false,
_removedConnection: false,
_removedContLen: false,
_removedTE: false,
_contentLength: null,
_hasBody: true,
_trailer: '',
finished: false,
_headerSent: true,
socket: [Socket],
connection: [Socket],
_header: 'POST / HTTP/1.1\r\nAccept: application/json, text/plain, */*\r\nContent-Type: application/json;charset=utf-8\r\nUser-Agent: axios/0.18.0\r\nContent-Length: 117\r\nHost: localhost:7076\r\nConnection: close\r\n\r\n',
_onPendingData: [Function: noopPendingOutput],
agent: [Agent],
socketPath: undefined,
timeout: undefined,
method: 'POST',
path: '/',
_ended: false,
res: null,
aborted: undefined,
timeoutCb: null,
upgradeOrConnect: false,
parser: null,
maxHeadersCount: null,
_redirectable: [Circular],
[Symbol(isCorked)]: false,
[Symbol(outHeadersKey)]: [Object] ,
_currentUrl: 'http://localhost:7076/' ,
response: undefined
我觉得我已经尝试了无数种配置。我没有得到什么?
【问题讨论】:
在我的情况下,使用http://localhost:8080
而不是 localhost:8080
就可以了。谢谢你给我这个主意。
【参考方案1】:
这是 4 个月后的事了,但我一直在试图弄清楚同样的事情。
尝试像这样更改您的实例配置:
const rpc = axios.create(
baseURL: 'localhost:7076',
proxy: false
)
我找不到解决方案,所以我最终挖掘了 axios 的代码。
我在 /lib/adapters/http.js 的第 89 行找到了这个:
var proxy = config.proxy;
if (!proxy && proxy !== false)
var proxyEnv = protocol.slice(0, -1) + '_proxy';
var proxyUrl = process.env[proxyEnv] || process.env[proxyEnv.toUpperCase()];
if (proxyUrl)
var parsedProxyUrl = url.parse(proxyUrl);
proxy =
host: parsedProxyUrl.hostname,
port: parsedProxyUrl.port
;
if (parsedProxyUrl.auth)
var proxyUrlAuth = parsedProxyUrl.auth.split(':');
proxy.auth =
username: proxyUrlAuth[0],
password: proxyUrlAuth[1]
;
if (proxy)
options.hostname = proxy.host;
options.host = proxy.host;
options.headers.host = parsed.hostname + (parsed.port ? ':' + parsed.port : '');
options.port = proxy.port;
options.path = protocol + '//' + parsed.hostname + (parsed.port ? ':' + parsed.port : '') + options.path;...
如果您的配置中没有代理条目或者您的代理条目不是假的(布尔值),我阅读它的方式。然后它使 var 'proxy' 等于它的默认代理。所以当它下降到第 110 行时......
if (proxy) ...
...有一个代理,(它刚刚创建的默认值),它将使用它。
当我将 proxy: false 添加到我的配置中时,axios 工作正常。
【讨论】:
为我工作,因为我在公司代理背后。【参考方案2】:您是否尝试过使用您的直接 IP? 输入你的终端:
网络统计
192.168.1.?
这个简单的答案/解释失败了,我在我的本地机器上设置了一个 Docker VM 并通过这个连接到我的个人 RPC API:
https://hub.docker.com/r/jlmconsulting/upcoind/
【讨论】:
用我的 ip 地址更新了,仍然无法访问 localhost 节点【参考方案3】:我遇到了同样的问题,试图从端口 8001 上的 nodejs express 应用程序向我机器上的端口 8000 上运行的另一个 Nodejs express 应用程序发出请求。对我有用的是这样写请求地址:
const testRequest = async () =>
try
const test = await axios.get('http://localhost:8000/test');
//rather than just localhost:8000/test
console.log('TEST', test);
catch (e)
console.error('TEST ERROR:', e);
;
它奏效了。我在您的 cmets 中看到您使用配置尝试过相同的操作,所以我觉得奇怪的是它不起作用...
【讨论】:
以上是关于Node.js / Axios 不会连接到 localhost的主要内容,如果未能解决你的问题,请参考以下文章
Heroku 上的 Node.js Express 应用程序不会使用 Mongoose 连接到 MongoLab 数据库
Socket.io 不会按需关闭套接字(并且不允许我的 swift 应用程序再次重新连接到 node.js 服务器)