http.request() method not working with urls having subdomains - node.js

I am trying to post some data like this
var options={hostname:'www.sub.domain.com',path:'post.php?'+qs.stringify(postData), method:'GET '};
and then calling this object with http.request(). It throws this error
events.js:71
throw arguments[1]; // Unhandled 'error' event
^
Error: Parse Error
at Socket.socketOnData (http.js:1485:20)
at TCP.onread (net.js:404:27)
What may be the issue?

Use host instead hostname in "option" object. Try as follows,
var options = {
host : 'www.sub.domain.com',
path:'/post.php?'+qs.stringify(postData),
method : 'GET'
};

Related

NodeJS : Error: read ECONNRESET at TCP.onStreamRead (internal/stream_base_commons.js:111:27)

Using Polling like below to check if the content of the file is changed then, other two functions are called
var poll_max_date=AsyncPolling(function (end,err) { if(err) {
console.error(err); } var stmp_node_id=fs.readFileSync(path.join(__dirname,'node_id'),"utf8");
console.log("--------loaded node : "+stmp_node_id);
if(druid_stmp_node_id!=stmp_node_id) {
// MAX DATA CUT-OFF DRUID QUERY
druid_exe.max_date_query_fire();
// // DRUID QUERY FOR GLOBAL DATA
druid_exe.global_druid_query_fire();
druid_stmp_node_id=stmp_node_id; }
end(); }, 1800000).run();//30 mins
Its working fine for sometime, but then getting below error like after 4 - 5hours :
events.js:167
throw er; // Unhandled 'error' event
^
Error: read ECONNRESET
at TCP.onStreamRead (internal/stream_base_commons.js:111:27) Emitted 'error' event at:
at emitErrorNT (internal/streams/destroy.js:82:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:50:3)
tried using fs.watch to monitor the changes in the file instead of polling like below :
let md5Previous = null; let fsWait = false;
fs.watch(dataSourceLogFile, (event, filename) => { if (filename) {
if (fsWait) return;
fsWait = setTimeout(() => {
fsWait = false;
}, 1000);
const md5Current = md5(fs.readFileSync(dataSourceLogFile));
if (md5Current === md5Previous) {
return;
}
md5Previous = md5Current;
console.log(`${filename} file Changed`);
// MAX DATA CUT-OFF DRUID QUERY
druid_exe.max_date_query_fire();
// DRUID QUERY FOR GLOBAL DATA
druid_exe.global_druid_query_fire(); } });
Its is also working fine for sometime, but then getting same error like after 4 - 5hours :
events.js:167 throw er; // Unhandled 'error' event ^
Error: read ECONNRESET at TCP.onStreamRead
(internal/stream_base_commons.js:111:27) Emitted 'error' event at: at
emitErrorNT (internal/streams/destroy.js:82:8) at emitErrorAndCloseNT
(internal/streams/destroy.js:50:3)
But when run in Local Machine, its working fine. the error occurs only when run in remote Linux Machine.
somebody can help me how I can fix that problem?
Use fs.watchFile once , because fs.watch is not consistent across platforms,
https://nodejs.org/docs/latest/api/fs.html#fs_fs_watchfile_filename_options_listener
Change your code according to the requirement.
It has been happening since the users are closing the browser before the data request is received, leading to Connection Reset.
Used PM2 (http://pm2.keymetrics.io/) to run the application, and it is working great now .

Strange error using socket.io with Node js

I'm trying to send some messages to a server.
That's what I do
for(var i=0; i<100; i++){
var post={
att1 : var.att[i].att1,
att2 : var.att[i].att2,
att3 : var.att[i].att3,
att4 : var.att[i].att4
}
sock.write(JSON.stringify(post));
}
But I get this strange error
events.js:72
throw er; // Unhandled 'error' event
^
Error: write EPIPE
at errnoException (net.js:904:11)
at Object.afterWrite (net.js:720:19)
logout
Why this happens? Is the buffer of the socket full?
It usually means that the other end closed the connection unexpectedly. In any case, you were writing to the closed socket.
Also, 100.length is not a valid JavaScript.

RESTIFY: Error: socket hang up] code: 'ECONNRESET' on multiple requests

I am implementing a node app, which brings in order details from BigCommerce.
Multiple calls are made to BigCommerce API asynchronously using Restify JsonClient.
It works fine for some calls but after that i gives error: [Error: socket hang up] code: 'ECONNRESET', sslError: undefined, body: {}
I have tried turning off socket pooling ie by setting agent=false, but it still gives same error.
Following is code which makes call to BigCommerce API
makeRequest = function (url, params, headers, orderDetails, cb) {
var options = {
headers: headers
};
var client = restify.createJsonClient({
url: url
});
client.get(options, function(err, req, res, obj) {
if(err){
console.log(err);
cb(err,obj);
} else if(obj != null) {
var result = obj;
if(orderDetails == null) {
cb(null,result);
} else {
cb(null, result , orderDetails);
}
}
});
};
I get following error:
{ [Error: socket hang up] code: 'ECONNRESET', sslError: unde
fined, body: {} } Error: socket hang up
at SecurePair.error (tls.js:993:23)
at EncryptedStream.CryptoStream._done (tls.js:689:22)
at CleartextStream.read [as _read] (tls.js:490:24)
at CleartextStream.Readable.read (_stream_readable.js:320:10)
at EncryptedStream.onCryptoStreamFinish (tls.js:301:47)
at EncryptedStream.g (events.js:175:14)
at EncryptedStream.EventEmitter.emit (events.js:117:20)
at finishMaybe (_stream_writable.js:352:12)
at endWritable (_stream_writable.js:359:3)
at EncryptedStream.Writable.end (_stream_writable.js:337:5)
at EncryptedStream.CryptoStream.end (tls.js:628:31)
at Socket.onend (_stream_readable.js:483:10)
Why am i getting such error? How can i handle it?
Thanks
I just wanted to make sure that you're setting the agent setting in the right area.
Include the
"agent": false
in your options. (It's not set in the options in the code you pasted)
Per gfpacheco in the comments here: https://github.com/restify/node-restify/issues/485
By default NodeJS uses agents to keep the TCP connection open, so you can reuse it.
The problem is that if the server is closed, or it closes your connection for whatever reason you get the ECONNRESET error.
To close the connection every time you just need to set agent: false in your client creation
I've tried this solution and it worked for me.
Other than that, the
"secureOptions": "constants.SSL_OP_NO_TLSv1_2"
solution posted here sounds like it could be the right path, since you're getting an sslError.
Maybe you are running into this issue https://github.com/joyent/node/issues/5360
TL;DR: You could try with latest node version and secureOptions: constants.SSL_OP_NO_TLSv1_2 added to your options.

ForEachLine() in node.js

Referring to slide no 35 in ppt on slideshare
When I run this code
var server = my_http.createServer();
server.on("request", function(request,response){
var chunks = [];
output = fs.createWriteStream("./output");
request.on("data",function(chunk){
chunks = forEachLine(chunks.concat(chunk),function(line){
output.write(parseInt(line,10)*2);
output.write("\n");
})
});
request.on("end",function(){
response.writeHeader(200,{"Content-Type":"plain/text"})
response.end("OK\n");
output.end()
server.close()
})
});
server.listen("8080");
I get error as
chunks = forEachLine(chunks.concat(chunk),function(line){
^
ReferenceError: forEachLine is not defined
Of course I unserstand that I need to include some library but when I googled this I found nothing . Since I am complete newbie to this I have absolutely no idea how to resolve it.
Any suggestions will be appreciable.
EDIT
Using the suggested answer I am getting error as
events.js:72
throw er; // Unhandled 'error' event
^
TypeError: Invalid non-string/buffer chunk
at validChunk (_stream_writable.js:150:14)
at WriteStream.Writable.write (_stream_writable.js:179:12)
at /var/www/html/experimentation/nodejs/first.js:18:20
at Array.forEach (native)
at forEachLine (/var/www/html/experimentation/nodejs/first.js:8:60)
at IncomingMessage.<anonymous> (/var/www/html/experimentation/nodejs/first.js:17:18)
at IncomingMessage.EventEmitter.emit (events.js:95:17)
at IncomingMessage.<anonymous> (_stream_readable.js:736:14)
at IncomingMessage.EventEmitter.emit (events.js:92:17)
at emitReadable_ (_stream_readable.js:408:10)
Thanks
See proxy_stream.js
function forEachLine(chunks, callback) {
var buffer = chunks.join("")
buffer.substr(0, buffer.lastIndexOf("\n")).split("\n").forEach(callback)
return buffer.substr(buffer.lastIndexOf("\n") + 1).split("\n")
}
The link to the repo was on the first slide.
EDIT BY LET's CODE FOR ERROR MESSAGE
Came to know the actual issue now .
I was using nod v0.10 and it is buggy in getting the streams so I was getting the error. Downgraded to v0.8 and same code is working perfect .

Node Redis Client Not Working With Method "HMSET"

I have the following code block that fails:
this.redisClient.hmset('user:' + userObj.getUserId(), {
'userId' : userObj.getUserId(),
'salutation' : userObj.getSalutation(),
'fn' : userObj.getFn(),
'mi' : userObj.getMi(),
'ln' : userObj.getLn(),
'suffix' : userObj.getSuffix(),
'userType' : userObj.getUserType(),
'created' : userObj.getCreated()
});
The error stack is as follows:
node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
TypeError: Cannot call method 'hmset' of undefined
at /node_apps/oc/api/v1/routes/user/db.user.js:70:34
at try_callback (/node_apps/oc/api/v1/node_modules/redis/index.js:484:9)
at RedisClient.return_reply (/node_apps/oc/api/v1/node_modules/redis/index.js:555:13)
at HiredisReplyParser.<anonymous> (/node_apps/oc/api/v1/node_modules/redis/index.js:256:14)
at HiredisReplyParser.emit (events.js:67:17)
at HiredisReplyParser.execute (/node_apps/oc/api/v1/node_modules/redis/lib/parser/hiredis.js:43:18)
at RedisClient.on_data (/node_apps/oc/api/v1/node_modules/redis/index.js:440:27)
at Socket.<anonymous> (/node_apps/oc/api/v1/node_modules/redis/index.js:70:14)
at Socket.emit (events.js:67:17)
at TCP.onread (net.js:329:14)
I am running Node 0.6.17 with Node Redis client. Any insight? Thanks!
If Node thinks you're calling hmset on undefined, that means it thinks that this.redisClient is undefined; quite often, this is because the value of this is not what you think it is (although it could be that redisClient wasn't initialized, etc). While it's impossible to say without seeing the surrounding code and how it's called, check to make sure the value of this is bound, if necessary.

Resources