node-fetch even though server is online it keeps saying errconrefused - node.js

Connecting to the server through browser is possible and i get http code 200, I have directly copied the url from the browser to the node fetch:
await fetch(`http://localhost:9000/renderAvatar.3d?pant=http://localhost/assets/2.png&face=http://localhost/assets/0.png&shirt=http://localhost/assets/1.png&name=de&trick=e`)
The other server on the 9000 port is written in c# and has code like this:
HttpListener httpServer;
public void SomeFunction() {
//Some boilerplate for http server definitely not stolen amogus
httpServer = new HttpListener();
httpServer.Prefixes.Add("http://localhost:9000/");
httpServer.Start();
Task demo = Server();
demo.GetAwaiter().GetResult();
}
public async Task server() {
while(true) {
HttpListenerContext ctx = await httpServer.GetContextAsync();
HttpListenerRequest req = ctx.Request;
HttpListenerResponse resp = ctx.Response;
if(req.HttpMethod == "GET") {
if(req.Url.AbsolutePath.ToString() == "/renderAvatar.3d") {
var parameters = HttpUtility.ParseQueryString(req.Url.Query);
if(parameters.Count > 3) {
var pant = parameters[0].ToString();
var face = parameters[1].ToString();
var shirt = parameters[2].ToString();
var name = parameters[3].ToString();
// can't share more code due this is propertiary code
any access from the browser works but why node fetch doesn't work, i have very bad solution to this issue using chrome to open up avatar renderer then close the chrome programatically but this uses way too much memory and quite unncesary.
(This is on linux btw, port 9000 shouldn't be protected by firewall and this is a local server)
thrown error:
FetchError: request to http://127.0.0.1:9000/renderAvatar.3d?pant=http://localhost/assets/2.png&face=http://localhost/assets/0.png&shirt=http://localhost/assets/1.png&name=de&trick=e failed, reason: connect ECONNREFUSED 127.0.0.1:9000
at ClientRequest.<anonymous> (file:///home/
(confidental)/backend/node_modules/node-fetch/src/index.js:108:11)
at ClientRequest.emit (node:events:527:28)
at Socket.socketErrorListener (node:_http_client:454:9)
at Socket.emit (node:events:527:28)
at emitErrorNT (node:internal/streams/destroy:157:8)
at emitErrorCloseNT (node:internal/streams/destroy:122:3)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
type: 'system',
errno: 'ECONNREFUSED',
code: 'ECONNREFUSED',
erroredSysCall: 'connect'
}

Turns out changing localhost to 127.0.0.1 on the c# app solves the issue, on linux localhost is automatically converted to 127.0.0.1 but c# app doesn't do that for some odd reason.
httpServer.Prefixes.Add("http://localhost:9000/");
to
httpServer.Prefixes.Add("http://127.0.0.1:9000/");

Related

Fetch error when refreshing page with await block in SvelteKit

I am building a sveltekit app that crashes when I refresh the page. Below is the code for the Home page that displays a map with points. The points are fetched from an api (also running on localhost). I initially had the await call inside an onMount function (worked fine) but I thought it would be tidier to use an await block. When the app is running everything works great - I can navigate to and from the Home page and the map loads as expected. However, if I refresh the browser on the Home page or navigate directly to the Home page after starting the app it crashes.
Update:
I now realize that using an await block or sveltkit's load function will run the fetch function on the server side before the page loads. This appears to fail because the map component relies on window. Disabling SSR fixes the issue although I would expect that the data object could be fetched via a load function and this not interfere with component creation, i.e. SSR shouldn't need to be disabled.
Svelte page:
<script>
const API_PATH = import.meta.env.VITE_API_PATH;
import Map from '$lib/Leaflet/Map.svelte';
import Point from '$lib/Leaflet/Vector/Point.svelte';
const lat = -41.273;
const lng = 173.279;
const zoom = 15;
async function getSites() {
const res = await fetch(API_PATH + '/sites');
const sites = await res.json();
if (res.ok) {
return sites;
} else {
throw new Error(sites);
}
}
let promise = getSites();
</script>
<svelte:head>
<title>Home</title>
</svelte:head>
<main>
<Map center={[lat, lng]} {zoom}>
{#await promise then sites}
{#each Object.values(sites['features']) as site}
<Point lat={site['geometry']['coordinates'][1]} lng={site['geometry']['coordinates'][0]}>
</Point>
{/each}
{/await}
</Map>
</main>
I get the following error in terminal:
Got request /
file:///.../node_modules/#sveltejs/kit/dist/install-fetch.js:6246
reject(new FetchError(`request to ${request.url} failed, reason: ${error.message}`, 'system', error));
^
FetchError: request to http://localhost:8000/sites failed, reason: connect ECONNREFUSED ::1:8000
at ClientRequest.<anonymous> (file:///.../node_modules/#sveltejs/kit/dist/install-fetch.js:6246:11)
at ClientRequest.emit (node:events:520:28)
at Socket.socketErrorListener (node:_http_client:442:9)
at Socket.emit (node:events:520:28)
at emitErrorNT (node:internal/streams/destroy:164:8)
at emitErrorCloseNT (node:internal/streams/destroy:129:3)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
type: 'system',
errno: 'ECONNREFUSED',
code: 'ECONNREFUSED',
erroredSysCall: 'connect'
}
And in the browser console:
Loading failed for the module with source “http://localhost:3000/#fs/.../.svelte-kit/runtime/client/start.js”.
Thanks for the support.

process.env["NODE_TLS_REJECT_UNAUTHORIZED"] = 0 not working

I'm using the node sendmail package which is giving me this error:
Error on connectMx for: Error: self signed certificate
at TLSSocket.onConnectSecure (_tls_wrap.js:1515:34)
at TLSSocket.emit (events.js:400:28)
at TLSSocket._finishInit (_tls_wrap.js:937:8)
at TLSWrap.ssl.onhandshakedone (_tls_wrap.js:709:12) {
code: 'DEPTH_ZERO_SELF_SIGNED_CERT'
}
So I put this in my code in like 5 places
process.env["NODE_TLS_REJECT_UNAUTHORIZED"] = 0;
Node says this warning when I run it:
Warning: Setting the NODE_TLS_REJECT_UNAUTHORIZED environment variable to '0' makes TLS connections and HTTPS requests insecure by disabling certificate verification.
Yet I still get the error message. It's coming from this code:
const {createConnection} = require('net');
createConnection(smtpPort, data[i].exchange); // problem code
sock.on('error', function (err) {
logger.error('Error on connectMx for: ', data[i], err);
tryConnect(++i)
});
Is this a bug in NodeJS, or am I messing something up? Thanks for the help.

Connection timed out while connecting to AWS DocumentDB outside the VPC

I'm trying create a very simple node app that can use DocumentDB. I'm not using Cloud9 neither Lambda, I'm coding locally. I was following this link https://docs.aws.amazon.com/documentdb/latest/developerguide/connect-from-outside-a-vpc.html and this link https://docs.aws.amazon.com/documentdb/latest/developerguide/connect-ec2.html
I created a poorly secured EC2 instance with the following inbound rules
port range
protocol
source
security group
22
TCP
0.0.0.0/0
demoEC2
This demoEC2 security group has the following inbound rules
type
protocol
port range
source
SSH
TCP
22
0.0.0.0/0
Then I created a DocumentDB cluster with 1 instance available that belongs to a security group that has the following inbound rules
type
protocol
port range
source
custom tcp
TCP
27017
demoEC2
After that, I open my terminal and created a tunnel:
ssh -i "mykeypair.pem" -L 27017:<CLUSTER ENDPOINT>:27017 ec2-user#<EC2 PUBLIC IPV4 DNS> -N
And, to test if my tunnel is working, I connect using mongoshell:
> mongo "mongodb://<MASTER USERNAME>:<MASTER PASSWORD>#localhost:27017/<DATABASE>" --tls --tlsAllowInvalidHostnames --tlsCAFile rds-combined-ca-bundle.pem
MongoDB shell version v4.2.13
connecting to: mongodb://localhost:27017/<DATABASE>?compressors=disabled&gssapiServiceName=mongodb
2021-07-29T10:10:59.309+0200 W NETWORK [js] The server certificate does not match the host name. Hostname: localhost does not match docdb-2021-07-27-10-32-49.ctuxybn342pe.eu-central-1.docdb.amazonaws.com docdb-2021-07-27-10-32-49.cluster-ctuxybn342pe.eu-central-1.docdb.amazonaws.com docdb-2021-07-27-10-32-49.cluster-ro-ctuxybn342pe.eu-central-1.docdb.amazonaws.com , Subject Name: C=US,ST=Washington,L=Seattle,O=Amazon.com,OU=RDS,CN=docdb-2021-07-27-10-32-49.ctuxybn342pe.eu-central-1.docdb.amazonaws.com
Implicit session: session { "id" : UUID("63340995-54ad-471b-aa8d-85763f3c7281") }
MongoDB server version: 4.0.0
WARNING: shell and server versions do not match
Warning: Non-Genuine MongoDB Detected
This server or service appears to be an emulation of MongoDB rather than an official MongoDB product.
Some documented MongoDB features may work differently, be entirely missing or incomplete, or have unexpected performance characteristics.
To learn more please visit: https://dochub.mongodb.org/core/non-genuine-mongodb-server-warning.
rs0:PRIMARY>
However, when I try to connect in my node app:
const mongoose = require('mongoose');
const fs = require('fs');
const path = require('path');
const username = ...
const password = ...
const database = ...
const connstring = `mongodb://${username}:${password}#localhost:27017/${database}?tls=true&replicaSet=rs0&readPreference=secondaryPreferred`;
const certFile = path.resolve(__dirname, './rds-combined-ca-bundle.pem');
const certFileBuf = fs.readFileSync(certFile); //I tried this one in tlsCAFile option as well
mongoose.connect(connstring,
{
tlsCAFile: certFile,
useNewUrlParser: true,
tlsAllowInvalidHostnames: true,
}
).then(() => console.log('Connection to DB successful'))
.catch((err) => console.error(err, 'Error'));
I get a connection timeout error after a while:
> > node .\index.js
(node:12388) [MONGODB DRIVER] Warning: Current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
MongoNetworkError: failed to connect to server [<CLUSTER ENDPOINT WITHOUT HAVING .cluster->:27017] on first connect [MongoNetworkTimeoutError: connection timed out
at connectionFailureError (D:\projects\documentdb-connect\node_modules\mongoose\node_modules\mongodb\lib\core\connection\connect.js:345:14)
at TLSSocket.<anonymous> (D:\projects\documentdb-connect\node_modules\mongoose\node_modules\mongodb\lib\core\connection\connect.js:313:16)
at Object.onceWrapper (events.js:421:28)
at TLSSocket.emit (events.js:315:20)
at TLSSocket.Socket._onTimeout (net.js:481:8)
at listOnTimeout (internal/timers.js:549:17)
at processTimers (internal/timers.js:492:7)]
at Pool.<anonymous> (D:\projects\documentdb-connect\node_modules\mongoose\node_modules\mongodb\lib\core\topologies\server.js:441:11)
at Pool.emit (events.js:315:20)
at D:\projects\documentdb-connect\node_modules\mongoose\node_modules\mongodb\lib\core\connection\pool.js:564:14
at D:\projects\documentdb-connect\node_modules\mongoose\node_modules\mongodb\lib\core\connection\pool.js:1013:9
at D:\projects\documentdb-connect\node_modules\mongoose\node_modules\mongodb\lib\core\connection\connect.js:32:7
at callback (D:\projects\documentdb-connect\node_modules\mongoose\node_modules\mongodb\lib\core\connection\connect.js:283:5)
at TLSSocket.<anonymous> (D:\projects\documentdb-connect\node_modules\mongoose\node_modules\mongodb\lib\core\connection\connect.js:313:7)
at Object.onceWrapper (events.js:421:28)
at TLSSocket.emit (events.js:315:20)
at TLSSocket.Socket._onTimeout (net.js:481:8)
at listOnTimeout (internal/timers.js:549:17)
at processTimers (internal/timers.js:492:7) Error
Since I could connect using mongoshell, I think the tunnel is working and I can even do some inserts on it, but why Mongoose can't connect? I tried also using the MongoClient (const MongoClient = require('mongodb').MongoClient and MongoClient.connect(same everything)) but it didn't worked, I'm still getting the same timeout error.
Turns out all I need to do is to pass the username and password through the options, not in the connection string:
const connstring = `mongodb://localhost:27017/${database}`;
const certFile = path.resolve(__dirname, './rds-combined-ca-bundle.pem');
const certFileBuf = fs.readFileSync(certFile);
mongoose.connect(connstring,
{
tls: true,
tlsCAFile: certFile,
useNewUrlParser: true,
tlsAllowInvalidHostnames: true,
auth: {
username,
password
}
}
)

ECONNREFUSED when trying to use jsreport

The following code:
var output = '<p>Hello</p>';
require("jsreport").render({
template: {
content: output
}
}).then(function(out) {
out.result.pipe(res);
});
});
returns this error :
Error: { [Error: Error during rendering report: connect ECONNREFUSED]
code: 'ECONNREFUSED',
errno: 'ECONNREFUSED',
syscall: 'connect' }
I believe it's because it cannot connect to internal jsreport server, but don't know why. Any idea on how to debug it or why it happens ?
We changed the embedded jsreport to stand alone jsreport . So we use the remote client to connect to this stand-alone instance. Now it works ! I don't know why.

NodeJS Proxy Router Table

I'm trying to make a NodeJS http-proxy with a Router Table.
I saw some examples using http-proxy and try like this :
var httpProxy = require('http-proxy');
var proxyTable = {};
proxyTable['testproxy.com/toto'] = 'google.com:80';
proxyTable['testproxy.com/tata'] = 'gmail.com:80';
var httpOptions = {
router: proxyTable
};
console.log('Proxy Server Listening on port 80');
console.log('Requests to textproxy.com/toto (on port 80) are redirected to google.com:80');
console.log('Requests to textproxy.com/tata (on port 80) are redirected to gmail.com:80');
httpProxy.createServer(httpOptions).listen(80);
FYI : testproxy.com refer to 127.0.0.1.
It seems to work (it only intercepts request to testproxy.com/toto and tata) but when I try :
curl http://testproxy.com/toto
I have a NodeJS error :
var proxyReq = (options.target.protocol === 'https:' ? https : http).reque
^
TypeError: Cannot read property 'protocol' of undefined
at Array.stream [as 3] (D:\workspace\Proxy W_S\node_modules\http-proxy\l
ib\http-proxy\passes\web-incoming.js:103:35)
at ProxyServer.<anonymous> (D:\workspace\Proxy W_S\node_modules\http-pro
xy\lib\http-proxy\index.js:83:21)
at Server.closure (D:\workspace\Proxy W_S\node_modules\http-proxy\lib\ht
tp-proxy\index.js:125:43)
at Server.EventEmitter.emit (events.js:98:17)
at HTTPParser.parser.onIncoming (http.js:2108:12)
at HTTPParser.parserOnHeadersComplete [as onHeadersComplete] (http.js:121:23
)
at Socket.socket.ondata (http.js:1966:22)
at TCP.onread (net.js:525:27)
Is router table already supported by http-proxy module ?
I have to do a dynamic proxy, any idea ?
I'm new at NodeJS, and I'm stuck.
Thanks a lot for your answers.
Pierre-Luc
It seems that proxy table routing was removed from node-http-proxy when they released version 1.0.0.
However, they provided a new way of doing it using the new API:
https://blog.nodejitsu.com/node-http-proxy-1dot0/

Resources