How can I get Nodejs twitter-passport behind proxy? - node.js

I'm testing twitter auth using passport-twitter's nodejs module. I already created my Twitter app and configured everything like especified by tutorials. The problem is that i'm behind a corporative proxy and as far as i know, node doesn't have any global proxy configuration and do not respect system proxy configuration. This is the output i get when i try to authenticate using twitter-passport:
InternalOAuthError: Failed to obtain request token
at Strategy.OAuthStrategy._createOAuthError (/home/droid/WebstormProjects/passport-social-master/node_modules/passport-oauth1/lib/strategy.js:390:13)
at /home/droid/WebstormProjects/passport-social-master/node_modules/passport-oauth1/lib/strategy.js:244:40
at /home/droid/WebstormProjects/passport-social-master/node_modules/oauth/lib/oauth.js:543:17
at ClientRequest. (/home/droid/WebstormProjects/passport-social-master/node_modules/oauth/lib/oauth.js:421:9)
at emitOne (events.js:77:13)
at ClientRequest.emit (events.js:169:7)
at TLSSocket.socketErrorListener (_http_client.js:265:9)
at emitOne (events.js:77:13)
at TLSSocket.emit (events.js:169:7)
at connectErrorNT (net.js:996:8)
at doNTCallback2 (node.js:452:9)
at process._tickCallback (node.js:366:17)
So far, i have tried to set a global tunnel using this:
var globalTunnel = require('global-tunnel');
globalTunnel.initialize({
host: 'proxy.example.com',
port: 8080
});
In this case, all I get is this message:
TypeError: Request path contains unescaped characters.
at new ClientRequest (_http_client.js:54:11)
at exports.request (http.js:31:10)
at TunnelingAgent.http.request (/home/droid/WebstormProjects/passport-social-master/http-proxy.js:36:15)
at TunnelingAgent.createSocket (/home/droid/WebstormProjects/passport-social-master/node_modules/tunnel/lib/tunnel.js:116:25)
at TunnelingAgent.createSecureSocket [as createSocket] (/home/droid/WebstormProjects/passport-social-master/node_modules/tunnel/lib/tunnel.js:188:41)
at TunnelingAgent.addRequest (/home/droid/WebstormProjects/passport-social-master/node_modules/tunnel/lib/tunnel.js:80:8)
at new ClientRequest (_http_client.js:139:16)
at exports.request (http.js:31:10)
at Object.http.request (/home/droid/WebstormProjects/passport-social-master/http-proxy.js:36:15)
at Object.globalTunnel._defaultedAgentRequest (/home/droid/WebstormProjects/passport-social-master/node_modules/global-tunnel/index.js:211:38)
at Object.exports.request (https.js:173:15)
at Object.globalTunnel._defaultedAgentRequest (/home/droid/WebstormProjects/passport-social-master/node_modules/global-tunnel/index.js:211:38)
at exports.OAuth._createClient (/home/droid/WebstormProjects/passport-social-master/node_modules/oauth/lib/oauth.js:256:20)
at exports.OAuth._performSecureRequest (/home/droid/WebstormProjects/passport-social-master/node_modules/oauth/lib/oauth.js:371:19)
at exports.OAuth.getOAuthRequestToken (/home/droid/WebstormProjects/passport-social-master/node_modules/oauth/lib/oauth.js:542:8)
at Strategy.OAuthStrategy.authenticate (/home/droid/WebstormProjects/passport-social-master/node_modules/passport-oauth1/lib/strategy.js:242:21)
I tried too the semi-global proxy(http://blog.shaunxu.me/archive/2013/09/05/semi-global-proxy-setting-for-node.js.aspx) by Shaun Xu. I imported the modified require.js everywhere but nothing is working. So i'm getting without options...

Your problem :
An old dependence in global-tunnel. see global-tunnel Issue #13
Quick solution : updating node-tunnel dependency to 0.0.4 does not seems to work at the end since using it will redirect all requests to internet proxy vs only authentication requests.
It's an 'old' post but if someone has a similar problem:
Use case :
Server is behind an internet proxy
Server access local resources via http/https, for example an elasticsearch server that must not be requested via proxy
You are using passportJs with Authentication module witch requires an external token validation, for exemple google on https://accounts.google.com
Problem :
By default NodeJs does not take into account any system proxy setting
Company proxy does not forward internal request via internet proxy (eg: if proxy is set, all requests are going to internet proxy, not anymore in intranet or localhost)
Solution not working :
Setting system env HTTP_PROXY or HTTPS_PROXY does not works for 2 reasons:
NodeJs ignore them
Proxy is set for all requests, and you want only one specific request to go through proxy
Using a global proxy (global-tunnel or similar) will fails because they redirect all requests adding their own Agent (request.options.agent) and thus will forward all your traffic to your proxy. Not desired.
A Solution :
Use a similar code as global-tunnel, adding a whitelist to proxy only some hostnames.
I ve implemented and tested this solution with success : see https://github.com/bloublou2014/httpx-proxy-agent-config
Usage example :
var proxy = require('httpx-proxy-agent-config');
proxy.install({
http_proxy: 'http://yourProxy:3128',
https_proxy: 'http://yourHttpsProxy:3218',
// example for passportjs Google OAuth2 + Google+
whitelist: ['www.google.com','accounts.google.com', '173.194.66.95', '74.125.192.95', '209.85.201.95', 'www.googleapis.com']
});
// try to access a page via http request :
var http = require('http');
http.get('http://www.google.com', function (response) {
var body = '';
response.on('data', function (d) {
body += d;
});
response.on('end', function () {
console.log("Body=", body);
});
});
// try to access a page via https request
var https = require('https');
https.get('https://www.google.com', function (response) {
var body = '';
response.on('data', function (d) {
body += d;
});
response.on('end', function () {
console.log("Body=", body);
});
});

Related

How can I make a custom reverse-proxy (preferrably a Node.js one) with good performance?

I am making a chat-bot that is based on a HTTP Webhook API that sends requests via POST with JSON message in it's body. It runs in multithread across multiple servers. So here's the problem - when users send multiple commands at the same time, commands are being handled asynchronously, resulting in a mess - for example, if you send a command that increments some counter in database (I'm using MongoDB) twice at the same moment, the bot will answer twice with the same counter value, incrementing it only once in database.
So I've came up with an idea of some custom reverse-proxy with a queueing logic in it. This proxy would accept an HTTP request, transfer it to a chat-bot thread and remember the chat where the message came from. If another request will come from the same chat, it will put the request in some sort of queue and transfer it to the bot when the first one will complete.
I made this proxy on Node.js using uWebSockets.js as a HTTP server and native http.request as HTTP client to transfer requests, but it does not perform very well. When it's being used at the "real" load (2-3 requests/sec) it starts to spit out errors and the whole chatbot becomes unresponsive.
There's nothing special about request sending code - it just makes a request and then responses with status, headers and body that it got from backend.
In general these errors do occur:
Error: connect ECONNREFUSED x.x.x.x:3xxx
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1056:14) {
errno: 'ECONNREFUSED',
code: 'ECONNREFUSED',
syscall: 'connect',
address: 'x.x.x.x',
port: 3xxx
}
Error: socket hang up
at connResetException (internal/errors.js:559:14)
at Socket.socketCloseListener (_http_client.js:376:25)
at Socket.emit (events.js:208:15)
at TCP.<anonymous> (net.js:588:12) {
code: 'ECONNRESET'
}
I would like to hear any ideas about how can I fix my reverse-proxy or how can I use a ready one. Maybe there is a way to make a queueing mechanism without a custom reverse-proxy at all. I wanted to try bouncy module, but it seems to be deprecated with the last commit on GitHub made at 2014.
try this
// include dependencies
var express = require('express')
var proxy = require('http-proxy-middleware')
// proxy middleware options
var options = {
target: 'http://www.example.org', // target host
changeOrigin: true, // needed for virtual hosted sites
ws: true, // proxy websockets
pathRewrite: {
'^/api/old-path': '/api/new-path', // rewrite path
'^/api/remove/path': '/path' // remove base path
},
router: {
// when request.headers.host == 'dev.localhost:3000',
// override target 'http://www.example.org' to 'http://localhost:8000'
'dev.localhost:3000': 'http://localhost:8000'
}
}
// create the proxy (without context)
var exampleProxy = proxy(options)
// mount `exampleProxy` in web server
var app = express()
app.use('/api', exampleProxy)
app.listen(3000)
Use the Caching technique. This is likely because your server processes too much code and leads the socket server to fail.

How to send http(s) requests with Node.js to a Node.js server hosted with LocalTunnel

I have a very basic node.js server:
var http = require("http");
var server = http.createServer(function(req, res){
console.log("Got request");
res.writeHead(200, {"Content-Type":"text/plain"});
res.end("Hi there!");
});
server.listen(3004);
I can access this via my browser and via sending a request from a Node.js client:
var http = require("http");
var options = {
"hostname": "localhost",
"port": 3004,
"path": "/",
"method": "GET"
};
var req = http.request(options, function(res){
var data = "";
res.on("data", function(chunk){
data += chunk;
});
res.on("end", function(){
console.log(data);
});
});
req.on("error", function(e){
console.log(e.stack);
});
req.end();
Now if I use the localtunnel package to "host" this server ( lt --port 3004 ), I now get my new hostname that I should be able to access it from on the internet. And indeed, I can easily access it from the browser.
However, if I try to send an https (not http because lt uses https) request from the Node.js client, with the new hostname, the request is refused and I get this error:
Error: connect ECONNREFUSED 138.197.63.247:3004
at TCPConnectWrap.afterConnect [as oncomplete]
So is it not possible to access a node.js web server when it is hosted with localtunnel? Or if there is (maybe using a 3rd part module) can someone please guide me on how that would be done as google is of absolutely no help. Thanks in advance.
EDIT1: I should note that on the server side, the error message does suggest "checking my firewall, but I have no idea what in my firewall could be blocking this, I'm not sure what to do. (Remember that this works when connecting from the browser??)
EDIT2: BTW, I tried to completely remove my firewall (got same result)
Telebit is a similar service, albeit with slightly different goals, but I believe it will support your use case.
HTTPS (tls/ssl) is supported by way of Greenlock.js and Let's Encrypt, so you don't have to modify your node server or manually configure anything - the end-to-end encryption is handled automagically.
Install
curl https://get.telebit.io | bash
You can also install via npm... but that isn't the preferred install method at this time. There may be some caveats.
The random domain you get is attached to your account (hence the need for email).
Configure
./telebit http 4000
The general format is
./telebit <protocol> <port> [subdomain]
It's not just https, you can use it to tunnel anything over tls/ssl (plain tcp, ssh, openvpn, etc).
Custom domains are not yet a generally available feature, but they're on the horizon.
You need to use HTTPS module of Node.js in the server code to be able to access it via HTTPS protocol. Creating an HTTPS server requires a certificate and passphrase.
From the docs:
const https = require('https');
const fs = require('fs');
const options = {
pfx: fs.readFileSync('test/fixtures/test_cert.pfx'),
passphrase: 'sample'
};
https.createServer(options, (req, res) => {
res.writeHead(200);
res.end('hello world\n');
}).listen(8000);
The issue is that you are not sending your request with the right port. When you use a tunneling service like localtunnel, it hosts your server as HTTPS. Now usually the port used for HTTPS is port 443, so the options object should look something like this:
var options = {
"hostname": "whatever",
"port": 443, //HERE!
"path": "/",
"method": "GET"
};
The same goes for services like zeit or heroku that host your app from their cloud.

Read data from a url behind a proxy

WEB Server I want to connect to
I have a web service running in a private network. This server is a web service which I can see working in the browser if I set the socks proxy in the browser.
My Service
I need node.js server on my machine to use the socks proxy to connect and call the web server
My UseCase
I need to do post requests for xml data as well as do some get requests.
My Problem
My app is not able to connect to the server hidden behind the socks proxy.
I do not want to set the global proxy for node or anything, only for one part of the app.
Updated : Working Solution
While the answer directs in the correct direction, I will include the final working solution here for reference as it needed a few modifications to the examples on github
var shttp = require('socks5-http-client');
var options = {} ;
options.host = 'ip.of.web.service';
options.port = 1919; //port of webservice
options.path = '/control/getjson'; //path on webservice to get
options.socksPort = 8778; //socks proxy port
options.socksHost = 'ip.of.socks.proxy';
var req = shttp.get(options, function (res) {
res.setEncoding('utf8');
res.on('readable', function () {
callback(res); //send response to my function for further processing.
});
});
Using socks proxy is not natively supported in the built in http client object.
Following 2 libraries makes it easy to connect to http endpoints through a socks proxy. Give it a try
Use socks5-http-client for connecting to http endpoints
Use socks5-https-client for connecting to https endpoints

NodeJS - What does "socket hang up" actually mean?

I'm building a web scraper with Node and Cheerio, and for a certain website I'm getting the following error (it only happens on this one website, no others that I try to scrape.
It happens at a different location every time, so sometimes it's url x that throws the error, other times url x is fine and it's a different url entirely:
Error!: Error: socket hang up using [insert random URL, it's different every time]
Error: socket hang up
at createHangUpError (http.js:1445:15)
at Socket.socketOnEnd [as onend] (http.js:1541:23)
at Socket.g (events.js:175:14)
at Socket.EventEmitter.emit (events.js:117:20)
at _stream_readable.js:910:16
at process._tickCallback (node.js:415:13)
This is very tricky to debug, I don't really know where to start. To begin, what IS a socket hang up error? Is it a 404 error or similar? Or does it just mean that the server refused a connection?
I can't find an explanation of this anywhere!
EDIT: Here's a sample of code that is (sometimes) returning errors:
function scrapeNexts(url, oncomplete) {
request(url, function(err, resp, body) {
if (err) {
console.log("Uh-oh, ScrapeNexts Error!: " + err + " using " + url);
errors.nexts.push(url);
}
$ = cheerio.load(body);
// do stuff with the '$' cheerio content here
});
}
There is no direct call to close the connection, but I'm using Node Request which (as far as I can tell) uses http.get so this is not required, correct me if I'm wrong!
EDIT 2: Here's an actual, in-use bit of code that is causing errors. prodURL and other variables are mostly jquery selectors that are defined earlier. This uses the async library for Node.
function scrapeNexts(url, oncomplete) {
request(url, function (err, resp, body) {
if (err) {
console.log("Uh-oh, ScrapeNexts Error!: " + err + " using " + url);
errors.nexts.push(url);
}
async.series([
function (callback) {
$ = cheerio.load(body);
callback();
},
function (callback) {
$(prodURL).each(function () {
var theHref = $(this).attr('href');
urls.push(baseURL + theHref);
});
var next = $(next_select).first().attr('href');
oncomplete(next);
}
]);
});
}
There are two cases when socket hang up gets thrown:
When you are a client
When you, as a client, send a request to a remote server, and receive no timely response. Your socket is ended which throws this error. You should catch this error and decide how to handle it: whether retry the request, queue it for later, etc.
When you are a server/proxy
When you, as a server, perhaps a proxy server, receive a request from a client, then start acting upon it (or relay the request to the upstream server), and before you have prepared the response, the client decides to cancel/abort the request.
This stack trace shows what happens when a client cancels the request.
Trace: { [Error: socket hang up] code: 'ECONNRESET' }
at ClientRequest.proxyError (your_server_code_error_handler.js:137:15)
at ClientRequest.emit (events.js:117:20)
at Socket.socketCloseListener (http.js:1526:9)
at Socket.emit (events.js:95:17)
at TCP.close (net.js:465:12)
Line http.js:1526:9points to the same socketCloseListener mentioned by #Blender, particularly:
// This socket error fired before we started to
// receive a response. The error needs to
// fire on the request.
req.emit('error', createHangUpError());
...
function createHangUpError() {
var error = new Error('socket hang up');
error.code = 'ECONNRESET';
return error;
}
This is a typical case if the client is a user in the browser. The request to load some resource/page takes long, and users simply refresh the page. Such action causes the previous request to get aborted which on your server side throws this error.
Since this error is caused by the wish of a client, they don't expect to receive any error message. So, no need to consider this error as critical. Just ignore it. This is encouraged by the fact that on such error the res socket that your client listened to is, though still writable, destroyed.
console.log(res.socket.destroyed); //true
So, no point to send anything, except explicitly closing the response object:
res.end();
However, what you should do for sure if you are a proxy server which has already relayed the request to the upstream, is to abort your internal request to the upstream, indicating your lack of interest in the response, which in turn will tell the upstream server to, perhaps, stop an expensive operation.
Take a look at the source:
function socketCloseListener() {
var socket = this;
var parser = socket.parser;
var req = socket._httpMessage;
debug('HTTP socket close');
req.emit('close');
if (req.res && req.res.readable) {
// Socket closed before we emitted 'end' below.
req.res.emit('aborted');
var res = req.res;
res.on('end', function() {
res.emit('close');
});
res.push(null);
} else if (!req.res && !req._hadError) {
// This socket error fired before we started to
// receive a response. The error needs to
// fire on the request.
req.emit('error', createHangUpError());
req._hadError = true;
}
}
The message is emitted when the server never sends a response.
One case worth mentioning: when connecting from Node.js to Node.js using Express, I get "socket hang up" if I don't prefix the requested URL path with "/".
below is a simple example where I got the same error when I missed to add the commented code in below example. Uncommenting the code req.end() will resolve this issue.
var fs = require("fs");
var https = require("https");
var options = {
host: "en.wikipedia.org",
path: "/wiki/George_Washington",
port: 443,
method: "GET"
};
var req = https.request(options, function (res) {
console.log(res.statusCode);
});
// req.end();
I used require('http') to consume https service and it showed "socket hang up".
Then I changed require('http') to require('https') instead, and it is working.
Expanding on Blender's answer, this happens in a number of situations. The most common ones I run into are:
The server crashed.
The server refused your connection, most likely blocked by User-Agent.
socketCloseListener, as outlined in Blender's answer, is not the only place that hangup errors are created.
For example, found here:
function socketOnEnd() {
var socket = this;
var req = this._httpMessage;
var parser = this.parser;
if (!req.res) {
// If we don't have a response then we know that the socket
// ended prematurely and we need to emit an error on the request.
req.emit('error', createHangUpError());
req._hadError = true;
}
if (parser) {
parser.finish();
freeParser(parser, req);
}
socket.destroy();
}
You could try curl with the headers and such that are being sent out from Node and see if you get a response there. If you don't get a response with curl, but you do get a response in your browser, then your User-Agent header is most likely being blocked.
Another case worth mentioning (for Linux and OS X) is that if you use a library like https for performing the requests, or if you pass https://... as a URL of the locally served instance, you will be using port 443 which is a reserved private port and you might be ending up in Socket hang up or ECONNREFUSED errors.
Instead, use port 3000, f.e., and do an http request.
For request module users
Timeouts
There are two main types of timeouts: connection timeouts and read timeouts. A connect timeout occurs if the timeout is hit while your client is attempting to establish a connection to a remote machine (corresponding to the connect() call on the socket). A read timeout occurs any time the server is too slow to send back a part of the response.
Note that connection timeouts emit an ETIMEDOUT error, and read timeouts emit an ECONNRESET error.
This caused me issues, as I was doing everything listed here, but was still getting errors thrown. It turns out that calling req.abort() actually throws an error, with a code of ECONNRESET, so you actually have to catch that in your error handler.
req.on('error', function(err) {
if (err.code === "ECONNRESET") {
console.log("Timeout occurs");
return;
}
//handle normal errors
});
I had the same problem while using Nano library to connect to Couch DB. I tried to fine tune connection pooling with use of keepaliveagent library and it kept failing with socket hang up message.
var KeepAliveAgent = require('agentkeepalive');
var myagent = new KeepAliveAgent({
maxSockets: 10,
maxKeepAliveRequests: 0,
maxKeepAliveTime: 240000
});
nano = new Nano({
url : uri,
requestDefaults : {
agent : myagent
}
});
After some struggling I was able to nail the problem - as it came out it was very, very simple mistake. I was connecting to the database via HTTPS protocol, but I kept passing to my nano object a keepalive agent created as the examples for use of this library show (they rely on some defaults that use http).
One simple change to use HttpsAgent did the trick:
var KeepAliveAgent = require('agentkeepalive').HttpsAgent;
I think "socket hang up" is a fairly general error indicating that the connection has been terminated from the server end. In other words, the sockets being used to maintain the connection between the client and the server have been disconnected. (While I'm sure many of the points mentioned above are helpful to various people, I think this is the more general answer.)
In my case, I was sending a request with a payload in excess of 20K. This was rejected by the server. I verified this by removing text and retrying until the request succeeded. After determining the maximum acceptable length, I verified that adding a single character caused the error to manifest. I also confirmed that the client wasn't the issue by sending the same request from a Python app and from Postman. So anyway, I'm confident that, in my case, the length of the payload was my specific problem.
Once again, the source of the problem is anecdotal. The general problem is "Server Says No".
I had the same problem during request to some server. In my case, setting any value to User-Agent in headers in request options helped me.
const httpRequestOptions = {
hostname: 'site.address.com',
headers: {
'User-Agent': 'Chrome/59.0.3071.115'
}
};
It's not a general case and depends on server settings.
This error also can happen when working with http.request, probably your request is not finished yet.
Example:
const req = https.request(options, res => {})
And you always need to add this line: req.end()
With this function we will order to finish sending request.
As in documentation is said:
With http.request() one must always call req.end() to signify the end of the request - even if there is no data being written to the request body.
Also reason can be because of using app instance of express instead of server from const server = http.createServer(app) while creating server socket .
Wrong
const express = require('express');
const http = require('http');
const WebSocket = require('ws');
const app = express();
app.use(function (req, res) {
res.send({ msg: "hello" });
});
const wss = new WebSocket.Server({ server: app }); // will throw error while connecting from client socket
app.listen(8080, function listening() {
console.log('Listening on %d', server.address().port);
});
Correct
const express = require('express');
const http = require('http');
const WebSocket = require('ws');
const app = express();
app.use(function (req, res) {
res.send({ msg: "hello" });
});
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
server.listen(8080, function listening() {
console.log('Listening on %d', server.address().port);
});
it's been a long time but another case is when performing requests which takes a long time on the server side (more then 2 minutes which is the default for express) and the timeout parameter was not configured in the server side. In my case I was doing client->server->server request (Node.js express) and I should set the timeout parameter on each request router on the server and on the client.
So in both servers I needed to set the request timeout by using
req.setTimeout([your needed timeout])
on the router.
I do both web (node) and Android development, and open Android Studio device simulator and docker together, both of them use port 8601, it complained socket hang up error, after close Android Studio device simulator and it works well in node side. Don’t use Android Studio device simulator and docker together.
There seems to be one additional case here, which is Electron not being a fan of the "localhost" domain name. In my case I needed to change this:
const backendApiHostUrl = "http://localhost:3000";
to this:
const backendApiHostUrl = "http://127.0.0.1:3000";
After that the problem just went away.
This means that DNS resolution (local or remote) might be causing some problems too.
I got a similar error when using CouchDB on OCP cluster.
const cloudantSessionStore = sessionStore.createSessionStore(
{
type: 'couchdb',
host: 'https://' + credentials['host'],
port: credentials['port'],
dbName: 'sessions',
options: {
auth: {
username: credentials['username'],
password: credentials['password']
},
cache: false
}
}
Which should be "http", not "https", to connect with my CouchDB instance. Hope it could be helpful for anyone who is faced with similar issue.
In my case, it was because a application/json response was badly formatted (contains a stack trace). The response was never send to the server.
That was very tricky to debug because, there were no log. This thread helps me a lot to understand what happens.
In case you're using node-http-proxy, please be aware to this issue, which will result a socket hang-up error : https://github.com/nodejitsu/node-http-proxy/issues/180.
For resolution, also in this link, simply move declaring the API route (for proxying) within express routes before express.bodyParser().
Ran into this issue yesterday running my web application and node.js server through IntelliJ IDEA 2016.3.6. All I had to do was clear my cookies and cache in my Chrome browser.
If you are experiencing this error over a https connection and it's happening instantly it could be a problem setting up the SSL connection.
For me it was this issue https://github.com/nodejs/node/issues/9845 but for you it could be something else. If it is a problem with the ssl then you should be able to reproduce it with the nodejs tls/ssl package just trying to connect to the domain
I think worth noting...
I was creating tests for Google APIs. I was intercepting the request with a makeshift server, then forwarding those to the real api. I was attempting to just pass along the headers in the request, but a few headers were causing a problem with express on the other end.
Namely, I had to delete connection, accept, and content-length headers before using the request module to forward along.
let headers = Object.assign({}, req.headers);
delete headers['connection']
delete headers['accept']
delete headers['content-length']
res.end() // We don't need the incoming connection anymore
request({
method: 'post',
body: req.body,
headers: headers,
json: true,
url: `http://myapi/${req.url}`
}, (err, _res, body)=>{
if(err) return done(err);
// Test my api response here as if Google sent it.
})
I my case it's was not an error, but expected behavior for chrome browser. Chrome keeps tls connection alive (for speed i think), but node.js server stop it after 2 min and you get an error.
If you try GET request using edge browser, there will be no error at all.
If you will close chrome window - you will get error right away.
So what to do?
1)You can filter this errors, because they are not really errors.
2)Maybe there is a better solution :)
After a long debug into node js code, mongodb connection string, checking CORS etc, For me just switching to a different port number server.listen(port); made it work, into postman, try that too. No changes to proxy settings just the defaults.
I was using nano, and it took me a long time to figure out this error. My problem was I was using the wrong port. I had port 5948 instead of 5984.
var nano = require('nano')('http://localhost:5984');
var db = nano.use('address');
var app = express();
Might be your server or Socket connection crashes unexpectedly.
I had this error when running two applications on the same port by mistake.
I had a next.js app and another one in nest.js, running both on port 8080, when I looked at the .env files I realized that they had the same port, so I changed the one from nest.js to 3000 and everything worked.
I'm not saying that this is the reason for the error but it's a possibility.
Your problem might also come from an attempt to connect to an HTTP URL while your service is only published on HTTPS...
Definitely a time-consuming mistake!
Got "[GET] localhost:4200, Socket hang up" during Azure Static Web App (SWA) Emulator for Angular app.
Solution is to remove this from angular.json:
"headers": {"cross-origin-opener-policy": "same-origin-allow-popups"}

Nodejs error while trying to access sharepoint

I get the following error while trying to access SharePoint from nodejs
events.js:71
throw arguments[1]; // Unhandled 'error' event
^
Error: connect ECONNREFUSED
at errnoException (net.js:769:11)
at Object.afterConnect [as oncomplete] (net.js:760:19)
below is the code
var SP = require('sharepoint'),
site = //url,
username = //username,
password = //password;
var client = new SP.RestService(site),
contacts = client.list('Contacts');
var showResponse = function (err, data) {
console.log(data);
}
client.signin(username, password, function () {
// At this point, authentication is complete,
// so we can do requests.
// Example request: Get list items
// showResponse is used as callback function
contacts.get(showResponse)
});
The important part of that error message is ECONNREFUSED, meaning the connection was refused right away. That means it never got to the point of checking your username and password or anything.
You should double-check your value for site. Maybe the server is running on a different port or you have a typo in that value.
Depending on the SharePoint module implementation you've to pass the entire url addressing the REST service.
In SharePoint 2010 the entire REST Service url should look like this
http:// %%SharePointSiteUrl%% /_vti_bin/ListData.svc
You should double check the outgoing requests direction SharePoint by using fiddler or an alternative HTTP watcher.

Resources