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);
});
});
Related
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.');
})
});
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
[EDIT]
I figured it out. The code ends up like this:
//getTrelloJSON.js
var request = require('request');
'use strict';
function getProjJSON(requestURL, callback){
request.get({
url: requestURL,
json: true,
headers: {'User-Agent': 'request'}
}, (err, res, data) => {
if (err) {
console.log('Error:', err);
} else if (res.statusCode !== 200) {
console.log('Status:', res.statusCode);
} else {
callback(data);
}
});
}
module.exports.getProjJSON = getProjJSON;
And
//showData.js
var getJSON = require('./getTrelloJSON');
getJSON.getProjJSON('https://trello.com/b/saDpzgbw/ld40-gem-sorceress.json', (result) => {
var lists = result.lists;
console.log(lists);
});
I run node showData.js and it gets the json and then I can manipulate it as needed. I printed just to show it works.
[EDIT END]
I'm new to node.js and I am facing a noob problem.
This code is supposed to request a JSON from a public trello board and return an object with a section of trello's json (lists section).
The first console.log() does not work but the second does.
How do I make it wait for the completion of getProjJSON() before printing it?
var request = require('request');
'use strict';
//it fails
console.log(getProjJSON('https://trello.com/b/saDpzgbw/ld40-gem-sorceress.json'));
function getProjJSON(requestURL){
request.get({
url: requestURL,
json: true,
headers: {'User-Agent': 'request'}
}, (err, res, data) => {
if (err) {
console.log('Error:', err);
} else if (res.statusCode !== 200) {
console.log('Status:', res.statusCode);
} else {
//it works
console.log(data.lists);
return data.lists;
}
});
}
Node.js is all about callbacks.
And here you just not register the callbacks for data.
var client = require('http');
var options = {
hostname: 'host.tld',
path: '/{uri}',
method: 'GET', //POST,PUT,DELETE etc
port: 80,
headers: {} //
};
//handle request;
pRequest = client.request(options, function(response){
console.log("Code: "+response.statusCode+ "\n Headers: "+response.headers);
response.on('data', function (chunk) {
console.log(chunk);
});
response.on('end',function(){
console.log("\nResponse ended\n");
});
response.on('error', function(err){
console.log("Error Occurred: "+err.message);
});
});
or here is a full example, hope this solve your problem
const postData = querystring.stringify({
'msg' : 'Hello World!'
});
const options = {
hostname: 'www.google.com',
port: 80,
path: '/upload',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(postData)
}
};
const req = http.request(options, (res) => {
console.log(`res_code: ${res.statusCode}`);
console.log(`res_header: ${JSON.stringify(res.headers)}`);
res.setEncoding('utf8');
res.on('data', (chunk) => {
console.log(`res_data: ${chunk}`);
});
res.on('end', () => {
console.log('end of response');
});
});
req.on('error', (e) => {
console.error(`response error ${e.message}`);
});
//write back
req.write(postData);
req.end();
I have a larger process running through a large collection of locations/devices in an API response and I'm trying to get to individual devices and turn that into a response my target system will understand. However it seems my inline HTTP request is not firing.
I've tried moving the callback out of the 'end' event, but I'm not even getting the logging for earlier up in the function. The only logging output I get is the "getting status for zone xyz"
async.each(tempSystem.zones, function(zone, zoneCallback) {
var applianceDiscovered = {};
console.log("getting status for zone", zone);
var options = {
host: host,
path: '/webapi/' + zone.zoneId + '/status',
headers: {'Authorization' : 'Bearer ' + accessToken}
};
var req = https.get(options, function(res) {
if (res.statusCode != 200) {
console.log("error ", res.statusCode);
}
console.log(res);
var bodyChunks = [];
res.on('data', function(chunk) {
bodyChunks.push(chunk);
});
res.on('end', function() {
if (res.statusCode === 200) {
console.log("get zone status: ", res.statusCode);
var body = Buffer.concat(bodyChunks);
var zoneStatus = JSON.parse(body);
console.log(zoneStatus);
zoneCallback();
} else {
console.log(res.statusCode);
}
});
res.on('error', function(error) {
console.log(error);
});
});
req.on('error', function(e) {
console.log("error: ", e);
});
}, function(err){
console.log("finished with zones");
});
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.
}
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();