socket hang up node 0.8.17 - node.js

I am getting a "socket hang up" error while doing a post request. I am not able to resolve it.
sparqlQ = getSPARQLPrefix() + query_string;
console.log(sparqlQ)
var options = {
host: process.env['SESAME_HOST'],
port: process.env['SESAME_PORT'],
method: 'POST',
path:
'/openrdf-sesame/repositories/myReo?update=' +
encodeURIComponent(sparqlQ) +
'&content-type=application/sparql-results+json',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/sparql-results+json',
},
};
var req = http.request(options, function(res) {
var data = "";
res.on('data', function (chunk) {
data += chunk;
});
res.on('error', function (error) {
console.log(error)
});
res.on('end', function () {
console.log(data)
req.end();
callback(null);
});
}).on('error', function(e) {
console.alert("Error getting sesame response [%s]", e.message);
req.end();
callback(e.message);
return
});
What am I doing wrong? Please help!

Two things to mention here.
You are not calling req.end() on your http request.
refer this documentation on the http module of node.js.
With http.request() one must always call req.end() to signify that
you're done with the request - even if there is no data being written
to the request body.
on the req.error event you are calling console.alert which i think should be console.log
Here is a sample code
http = require("http");
var options = {
host: "localhost",
port: 80,
method: 'POST'
};
var req = http.request(options, function(res) {
var data = "";
res.on('data', function (chunk) {
data += chunk;
});
res.on('error', function (error) { });
res.on('end', function () {
console.log(data)
req.end();
console.log(null);
});
}).on('error', function(e) {
console.log("Error getting sesame response [%s]", e.message);
req.end();
console.log(e.message);
return
});
req.end();

Related

Unable to parse InputStreamResource response in nodejs

How to read InputStreamResource in nodejs?
Our REST API returns response as InputStreamResource. We need to convert this response as xlsx file or json format. Please help
Below is the code:
var options = {
host: 'xxxxxxxxxxxxxxxxx',
port: xxxxx,
path: '/eeeeee/axxxxxxx?code=' + req.query.code,
method: 'GET',
headers:{
'user_id': req.headers.user_id,
'access_token': req.headers.access_token
}
};
var req = https.request(options, function (res) {
var decoder = new StringDecoder('utf8');
res.on('data', function(chunk) {
console.log(chunk)
var textChunk = decoder.write(chunk);
console.log(textChunk)
});
});
req.end();
req.on('error', function(e) {
console.error(e);
});
Response is getting this way ...
enter image description here
var req = https.request(options, function (res) {
var resData = ''
res.setEncoding('binary')
res.on('data', function(chunk){
resData += chunk
})
res.on('end', function(){
// fs.writeFile('message1.xlsx', resData, 'binary', function(err){
// if (err) throw err
// console.log('File saved.')
// })
var new_wb = XLSX.read(resData, {type:'binary'});
console.log('File saved.');
})
});

Using Q library for HTTP api response testing in nodejs

how to use Q to make it wait until previous response has come from the server.
What I am looking to do here is compare the response from test server and production server for the same request.
I get the responses back from both the servers, but unable to compare them since the assert statement is executed before the response comes back.
Any one know what I am doing wrong. heres the code.
var Q = require('q');
var path='';
var prodResponse = '';
var tstReponse = '';
Q.fcall(readFile())
.then(secondFunction())
.then(thirdFunction())
.then(function(){
console.log("prodResponse: "+prodResponse);
console.log("tstResponse: "+tstResponse);
assert.strictEqual(prodResponse, tstResponse)
})
.catch(function(){
console.log('error occurred');
})
.done();
function readFile(){
fs.readFile('hostname.json', function (err, data) {
if (err) return console.error(err);
path = JSON.parse(data);
return JSON.parse(data);
});
}
function secondFunction(){
var prodOptions = {
hostname: 'somehostname.com',
port: 80,
path: "/path?"+path.path,
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=UTF-8'
},
auth : ''
};
return http.request(prodOptions, function(res) {
console.log('Prod');
res.setEncoding('utf8');
res.on('data', function (chunk) {
prodResponse = chunk;
return chunk;
});
res.on('end', function() {
console.log('No more data in response.');
})
}).on('error', function(e) {
console.log('problem with request: ' + e.message);
}).end();
}
function thirdFunction(){
// same a second, only difference is the response http.
}
There is multiple errors in your code
Q.fcall(readFile())
Your q variable is q and not Q. So this line will crash because Q is undefined (javascript is case sensitive).
Then, readFile doesn't return any promise (in fact, it returns nothing). So the q library can't use anything to wait the end of any asynchronous work. The then callbacks will be fired immediatly.
You can use Q.ninvoke to make your readFile function return a promise, and you can use Q.defer to create and return a promise from your secondFunction:
var Q = require('q');
var path='';
var prodResponse = [];
var tstReponse = '';
readFile()
.then(secondFunction())
.then(thirdFunction())
.then(function(){
console.log("prodResponse: "+prodResponse);
console.log("tstResponse: "+tstResponse);
assert.strictEqual(prodResponse, tstResponse)
})
.catch(function(){
console.log('error occurred');
})
.done();
function readFile(){
return Q.ninvoke(fs, 'readFile', 'hostname.json').then(function (data) {
path = JSON.parse(data);
return path;
}, function (err) {
console.error(err);
});
}
function secondFunction(){
var prodOptions = {
hostname: 'somehostname.com',
port: 80,
path: "/path?"+path.path,
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=UTF-8'
},
auth : ''
};
var defer = Q.defer();
var chunks = [];
http.request(prodOptions, function(res) {
console.log('Prod');
res.setEncoding('utf8');
res.on('data', function (chunk) {
chunks.push(chunk);
});
res.on('end', function() {
console.log('No more data in response.');
prodResponse = chunks.join('');
defer.resolve(prodResponse);
})
}).on('error', function(e) {
console.log('problem with request: ' + e.message);
defer.reject(e);
}).end();
return defer.promise;
}
function thirdFunction(){
// same a second, only difference is the response http.
}

Invoking Web Service(Soap) through nodejs Status Code error 415

I am trying to invoke WCF WebService (SOAP Request) via nodejs. I am getting 415(unsupported media type) http status error code. Any idea what I am missing?
var http = require('http');
var options = {
host:'localhost',
port:'34563',
path:'/Service1.svc',
connection:'keep-alive',
accept:'*/*',
method:'POST',
header: {
'Content-Type':'text/xml;charset="UTF-8"',
'Content-Length':data.length,
'Accept':'*/*',
'SOAPAction':'http://tempuri.org/IService1/GetData'
}
};
var req=http.request(options, function(res) {
console.log(res.statusCode);
res.on('data', function(data) {
console.log(data);
});
res.on('end', function() {
});
res.on('error', function(error) {
console.log('1'+error);
});
});
var data='<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">'+
'<s:Body>'+
'<GetData xmlns="http://tempuri.org/">'+
'<value>12</value>'+
'</GetData>'+
'</s:Body>' +
'</s:Envelope>';
req.write(data);
req.end();
damn... Its silly mistake,
it supposed to be headers, 's' missed.
var options = {
host:'localhost',
port:'34563',
path:'/Service1.svc',
connection:'keep-alive',
accept:'*/*',
method:'POST',
headers: {
'Content-Type':'text/xml;charset="UTF-8"',
'Content-Length':data.length,
'Accept':'*/*',
'SOAPAction':'http://tempuri.org/IService1/GetData'
}
};
var req=http.request(options, function(res) {
console.log(res.statusCode);
var body = '';
res.on('data', function(data) {
body += data;
});
res.on('end', function() {
console.log(body);
});
res.on('error', function(error) {
console.log(error);
});
});

ECONNRESET error node.js https

Guys I'm having trouble requesting to this URL.. It seems fine, but I always get the error ECONNRESET.
I wrote a little script in ruby and it worked fine. With cURL in the terminal also works.
I tried all the solutions on a lot of issues and stack overflow threads... Like these:
https://github.com/joyent/node/issues/5360
https://github.com/joyent/node/issues/5119
Any idea what it might be?
The url is: https://ecommerce.cielo.com.br/servicos/ecommwsec.do
var https = require('https');
var options = {
host: 'ecommerce.cielo.com.br',
path: '/servicos/ecommwsec.do',
//This is what changes the request to a POST request
method: 'GET',
};
https.globalAgent.options.secureProtocol = 'SSLv3_method';
callback = function(response) {
var str = ''
response.on('data', function (chunk) {
str += chunk;
});
response.on('end', function () {
console.log(str);
});
}
var req = https.request(options, callback);
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
How are you ??
Let's try this solution.
app.js
Change your options:
var options = {
host: 'ecommerce.cielo.com.br',
path:'/servicos/ecommwsec.do',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(body),
'user-agent': 'node.js'
}
};
https.globalAgent.options.secureProtocol = 'SSLv3_method';
try{
var req = https.request(options, function(res)
{
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log("body: " + chunk);
}).on('end', function(cieloResponse){
console.log( cieloResponse);
});
console.log('Response:' + res);
});
req.end();
}catch(err){
console.log('ERRO: '+ err);
}

Nodejs http request not working

I have a piece of code that's supposed to do a http get request. The program exited successfully without error, but I didn't see any response and it didn't even go inside the callback function! At first I thought it's because http is asynchronous and put a large loop in the end but that didn't work either. Does anyone know this issue? Only the first console log sendHttpRequest and 444 gets printed. I also tried the http.get but it didn't work either.
function sendHttpRequest (url, callBack) {
console.log("sendHttpRequest");
//constrct options
var options = {
host: 'www.google.com',
path: '/index.html',
method: 'GET',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
};
http.get("http://www.google.com/index.html", function(res) {
console.log("Got response: " + res.statusCode);
});
var req = http.request(options, function(res) {
console.log("333");
var output = '';
console.log(options.host + ':' + res.statusCode);
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log("DATATATAT!")
output += chunk;
});
res.on('end', function () {
console.log('222');
var obj = JSON.parse(output);
callBack(res.statusCode, obj);
});
});
req.on('error', function (err) {
console.log('error: ' + err.message);
});
req.end();
console.log("444");
}
}
Update
The grunt task terminated before the OP received a response; adding async and a callback to the task fixed it.
If I take your code outside of the function and prepend var http = require('http'); I get a response up until 222, at which point it dies with SyntaxError: Unexpected token <. Which is actually dying because you're trying to parse an HTML response as JSON.
If you paste the entire script below and run it end to end, the console dies with:
undefined:1
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
^
SyntaxError: Unexpected token <
at Object.parse (native)
at IncomingMessage.<anonymous> (/Users/you/nodetest/tmp/test.js:31:28)
at IncomingMessage.EventEmitter.emit (events.js:120:20)
at _stream_readable.js:896:16
at process._tickCallback (node.js:599:11)
The script:
var http = require('http');
console.log("sendHttpRequest");
//constrct options
var options = {
host: 'www.google.com',
path: '/index.html',
method: 'GET',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
};
http.get("http://www.google.com/index.html", function(res) {
console.log("Got response: " + res.statusCode);
});
var req = http.request(options, function(res) {
console.log("333");
var output = '';
console.log(options.host + ':' + res.statusCode);
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log("DATATATAT!")
output += chunk;
});
res.on('end', function () {
console.log('222');
// it's failing on the next line, because the output
// it's receiving from Google is HTML, not JSON.
// If you comment out this line and simply
// "console.log(output)" you'll see the HTML response.
var obj = JSON.parse(output);
callBack(res.statusCode, obj);
});
});
req.on('error', function (err) {
console.log('error: ' + err.message);
});
req.end();
console.log("444");

Resources