Nodejs, soap, callback is not a function - node.js

first i got pfx certficate which a exported it to pem and key with openssl (if this could be an issue). I trid to use client.setSecurity(new soap.ClientSSLSecurit ()) but then i get client undefined.
my code goes like this:
var soap = require('soap'),
fs = require('fs');
var url = 'tes.com';
var auth = "Basic " + new Buffer("user" + ":" + "password").toString("base64")
soap.createClient( url, {wsdl_options: {
cert: fs.readFileSync('cert/certificate.pem'),
key: fs.readFileSync('cert/certificate.key')
}
}, { wsdl_headers: {Authorization: auth} }, function(err, client) {
client.describe();
});
I am getting this error and do not know what is wrong:
callback(err, wsdl && new Client(wsdl, endpoint, options));
^
TypeError: callback is not a function
at D:\web\mobile\node_modules\soap\lib\soap.js:50:5
at D:\web\mobile\node_modules\soap\lib\soap.js:33:16
at D:\web\mobile\node_modules\soap\lib\wsdl.js:2167:9
at Request._callback (D:\web\mobile\node_modules\soap\lib\http.js:114:14)
at self.callback (D:\web\mobile\node_modules\request\request.js:187:22)
at emitOne (events.js:96:13)
at Request.emit (events.js:188:7)
at Request.onRequestError (D:\web\mobile\node_modules\request\request.js:813:8)
at emitOne (events.js:96:13)
at ClientRequest.emit (events.js:188:7)
tnx
miha

Your arguments is not correct. Please correct like this :
soap.createClient( url, {wsdl_options: {
cert: fs.readFileSync('cert/certificate.pem'),
key: fs.readFileSync('cert/certificate.key')
},
wsdl_headers: {Authorization: auth} }, function(err, client) {
client.describe();
});

Related

Howo to get IPP endpoint

I'm using the ipp npm module to send a print job from a google cloud function. I believe I have set up the printer correctly but I don't know how I'm supposed to know the exact uri for sending the print job.
The printer model is Brother MFC-L3770CDW
Here is how my settings look in the web view for the printer configuration.
And here is the function code.:
var ipp = require('ipp');
var PDFDocument = require('pdfkit');
var doc = new PDFDocument;
doc.text("Hello World");
var buffers = [];
doc.on('data', buffers.push.bind(buffers));
doc.on('end', function () {
var printer = ipp.Printer("https://10.0.0.55:443");
var file = {
"operation-attributes-tag":{
"requesting-user-name": "User",
"job-name": "Print Job",
"document-format": "application/pdf"
},
data: Buffer.concat(buffers)
};
printer.execute("Print-Job", file, function (err, res) {
if(err) {
console.log(err);
}
else{
console.log("Printed: "+res.statusCode);
}
});
console.log('executing');
});
doc.end();
console.log('finished executing');
I have tried various uris such as
https://10.0.0.55:631
https://10.0.0.55:443
https://10.0.0.55:631/ipp
https://10.0.0.55:631/ipp/printer
Sometimes I get an error like:
"Error: socket hang up
at TLSSocket.onHangUp (_tls_wrap.js:1148:19)
at Object.onceWrapper (events.js:313:30)
at emitNone (events.js:111:20)
at TLSSocket.emit (events.js:208:7)
at endReadableNT (_stream_readable.js:1064:12)
at _combinedTickCallback (internal/process/next_tick.js:139:11)
at process._tickCallback (internal/process/next_tick.js:181:9)
code: 'ECONNRESET',
path: null,
host: '10.0.0.55',
port: '631',
localAddress: undefined }"

Reading big .txt and checking if string contains on response body

I have this code:
var fs = require('fs');
var readline = require('readline');
var request = require("request");
var filename = process.argv[2];
readline.createInterface({
input: fs.createReadStream(filename),
terminal: false
}).on('line', function(line) {
sep = line.split("|");
id = sep[0];
name = sep[1];
var options = { method: 'POST',
url: 'https://api.com/mobile_authentications',
proxy: '...',
headers:
{ Host: 'api.com',
'Content-Type': 'application/json',
'Accept-Language': 'pt-BR',
'X-Client-Info': 'Timezone%3D-Infinity%26device_id%3D578e4ac016b69248%26utc_offset%3D-0300%26app_id%3D7092%26resolution%3D720x1280%26connectivity%3DWIFI%26site_id%3DMLB%26density%3D320%26user_id%3Dguest' },
body: '{"authentication_request":{"client_id":"'+id+'|'+name+'"}}' };
request(options, function (error, response, body) {
if (error) throw new Error(error);
if(body.includes('ATTEMPS'))
{
console.log("CAPTCHA");
}
//console.log(body);
});
});
First question: How can I check if body response contains "ATTEMPS" string?
Another problem: When the ids.txt file has more than 100 lines the script returns me this error:
if (error) throw new Error(error);
^
Error: Error: tunneling socket could not be established, statusCode=502
at Request._callback (C:\Users\PC\Desktop\top\convert.js:65:20)
at self.callback (C:\Users\PC\Desktop\top\node_modules\request\request.js:185:22)
at Request.emit (events.js:182:13)
at Request.onRequestError (C:\Users\PC\Desktop\top\node_modules\request\request.js:881:8)
at ClientRequest.emit (events.js:182:13)
at ClientRequest.onConnect (C:\Users\PC\Desktop\top\node_modules\tunnel-agent\index.js:168:23)
at Object.onceWrapper (events.js:273:13)
at ClientRequest.emit (events.js:182:13)
at Socket.socketOnData (_http_client.js:475:11)
at Socket.emit (events.js:182:13)
That is, the script is not able to work with large files?
Thanks.

Error: socket hang up in Http Request made in Node JS using request-promise causing for loop to restart

I am trying to make an Http Request using request-promise inside a for loop. But it seems if a Http Request takes long, request-promise closes the connection.
This behavior is ok but what I am not able to grasp is the for loop starts from 0 again after the error is printed.
Below is the code
const rp = require('request-promise');
async function stepIterator(processingSteps, documentId) {
var finalResult = null;
for (var step = 0, len = processingSteps.length; step < len; step++) {
if (step === 0 || step === 1 || step == 2 || step == 3) {
try {
console.log('Calling step ', step);
let url = 'http://internal-server:8080/process';
let collection = getCollection(documentId);
let splitText = getSPlit(documentId);
let outputFormat = 'xmi';
let documentObject = await callServer(url, collection, splitText, outputFormat);
finalResult = documentObject;
} catch (error) {
console.log("Error");
}
}
}
return finalResult;
}
async function callServer(url, collection, splitText, outputFormat) {
var options = {
method: 'POST',
uri: url,
headers: {
'Content-Type': 'multipart/form-data',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive '
},
formData: {
collection: collection,
text: splitText,
output: outputFormat
}
};
return rp(options)
}
The complete error trace is as follows
{ RequestError: Error: socket hang up
at new RequestError (D:\New_Projects\new-data-access-layer\node_modules\request-promise-core\lib\errors.js:14:15)
at Request.plumbing.callback (D:\New_Projects\new-data-access-layer\node_modules\request-promise-core\lib\plumbing.js:87:29)
at Request.RP$callback [as _callback] (D:\New_Projects\new-data-access-layer\node_modules\request-promise-core\lib\plumbing.js:46:31)
at self.callback (D:\New_Projects\new-data-access-layer\node_modules\request\request.js:185:22)
at Request.emit (events.js:182:13)
at Request.onRequestError (D:\New_Projects\new-data-access-layer\node_modules\request\request.js:881:8)
at ClientRequest.emit (events.js:182:13)
at Socket.socketOnEnd (_http_client.js:425:9)
at Socket.emit (events.js:187:15)
at endReadableNT (_stream_readable.js:1094:12)
at process._tickCallback (internal/process/next_tick.js:63:19) name: 'RequestError', message: 'Error: socket hang up', cause:
{ Error: socket hang up
at createHangUpError (_http_client.js:322:15)
at Socket.socketOnEnd (_http_client.js:425:23)
at Socket.emit (events.js:187:15)
at endReadableNT (_stream_readable.js:1094:12)
at process._tickCallback (internal/process/next_tick.js:63:19) code: 'ECONNRESET' }, error: { Error: socket hang up
at createHangUpError (_http_client.js:322:15)
at Socket.socketOnEnd (_http_client.js:425:23)
at Socket.emit (events.js:187:15)
at endReadableNT (_stream_readable.js:1094:12)
at process._tickCallback (internal/process/next_tick.js:63:19) code: 'ECONNRESET' }, options: { method: 'POST',
uri: 'http://internal-server:8080/process',
json: true,
headers: { Connection: 'keep-alive ' },
body:
{ docSplitId: [Array],
_id: 5c579d84812acb17ec74ac39,
contentType: 'application/pdf',
location:
'C:\\Users\\newuser\\AppData\\Local\\Temp\\2\\report.pdf',
docModelVersion: '1',
visualMetaDataId: null,
categoryId: '5c52a72f6df294140c0535bc',
deductedInfo: null,
status: 'New',
isDeleted: false,
metadata: [Object],
detailedStatus: [Array] },
callback: [Function: RP$callback],
transform: undefined,
simple: true,
resolveWithFullResponse: false,
transform2xxOnly: false }, response: undefined }
Obviously the socket is hanging! Don't bother with http, it is a little complex. Use node unirest and it closes the data stream.
var unirest = require('unirest');
var req = unirest('POST', 'localhost:3200/store/artifact/metamodel')
.attach('file', '/home/arsene/DB.ecore')
.field('description', 'We are trying to save the metamodel')
.field('project', '6256d72a81c4b80ccfc1768b')
.end(function (res) {
if (res.error) throw new Error(res.error);
console.log(res.raw_body);
});
Hope this helps!

If I disable NODE_TLS_REJECT_UNAUTHORIZED, my request is still denied

I am disabling Node from rejecting self signed certificates and making a request.
const { USER, PW } = process.env;
const b64 = new Buffer(`${VP_API_USER}:${VP_API_PW}`).toString("base64");
const Authorization = `Basic ${b64}`;
const doFind = async url => {
process.env.NODE_TLS_REJECT_UNAUTHORIZED = 0;
const results = await fetch(url, { headers: { Authorization } })
.then(r => (r.ok ? r.json() : Promise.reject(r)))
.catch(err => {
return Promise.reject(err);
});
process.env.NODE_TLS_REJECT_UNAUTHORIZED = 1;
return results;
};
I am still being rejected.
{ FetchError: request to https://<url>:55544/contracts failed, reason: connect ECONNREFUSED <url>:55544
at ClientRequest.<anonymous> (/Users/mjhamm75/Developer/sedd-monorepo/node_modules/node-fetch/index.js:133:11)
at emitOne (events.js:116:13)
at ClientRequest.emit (events.js:211:7)
at TLSSocket.socketErrorListener (_http_client.js:387:9)
at emitOne (events.js:116:13)
at TLSSocket.emit (events.js:211:7)
at emitErrorNT (internal/streams/destroy.js:64:8)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickCallback (internal/process/next_tick.js:180:9)
name: 'FetchError',
message: 'request to https://<url>:55544/contracts failed, reason: connect ECONNREFUSED <url>:55544',
type: 'system',
errno: 'ECONNREFUSED',
code: 'ECONNREFUSED' }
What am I doing wrong?
process.env.NODE_TLS_REJECT_UNAUTHORIZED = 1;
line should go inside the callback (your then or catch before the return. because a promise gets resolved in the callback, but your line
process.env.NODE_TLS_REJECT_UNAUTHORIZED = 1;
is written outside of it, even though it appears after the statement, it runs immediately without waiting for the callback. so, your tls is effectively never disabled.
I hope this helps:)
Previous answer looks incorrect - await postpones execution of next line until promise will be resolved.
According to the documentation the NODE_TLS_REJECT_UNAUTHORIZED value should be string '0' to disable TLS validation.
This is how I would approach it, if I had to reset the env var afterwards.
Using .finally() the statement will execute regardless of the outcome of the fetch.
const doFind = async url => {
process.env.NODE_TLS_REJECT_UNAUTHORIZED = 0;
const results = await fetch(url, { headers: { Authorization } })
.then(r => (r.ok ? r.json() : Promise.reject(r)))
.catch(err => {
return Promise.reject(err);
})
.finally(() => {
process.env.NODE_TLS_REJECT_UNAUTHORIZED = 1;
});
return results;
};

Cloud Functions for Firebase Image download function Error

I am building a web application using Firebase and the new feature Cloud Functions for Firebase. I have created a function that takes a URL and downloads the image into a 64-bit encoded string as below using the node modules request and request-promise-native:
module.exports = {
downloadImageFromUrl: function (url) {
var options = {
method: 'GET',
uri: url,
resolveWithFullResponse: true,
simple: false,
family: 4
};
return rp.get(options)
.then(function (res) {
return "data:" + res.headers["content-type"] + ";base64," + new Buffer(res.body).toString('base64');
})
.catch(function (error) {
console.log("ERROR GETTING image", error);
return error;
});
}
};
The top function works perfectly running locally but once on firebase it gives the error:
RequestError: Error: getaddrinfo EAI_AGAIN lh6.googleusercontent.com:443
at new RequestError (/user_code/node_modules/request-promise/node_modules/request-promise-core/lib/errors.js:14:15)
at Request.plumbing.callback (/user_code/node_modules/request-promise/node_modules/request-promise-core/lib/plumbing.js:87:29)
at Request.RP$callback [as _callback] (/user_code/node_modules/request-promise/node_modules/request-promise-core/lib/plumbing.js:46:31)
at self.callback (/user_code/node_modules/request/request.js:188:22)
at emitOne (events.js:96:13)
at Request.emit (events.js:188:7)
at Request.onRequestError (/user_code/node_modules/request/request.js:884:8)
at emitOne (events.js:96:13)
at ClientRequest.emit (events.js:188:7)
at TLSSocket.socketErrorListener (_http_client.js:310:9)
at emitOne (events.js:96:13)
at TLSSocket.emit (events.js:188:7)
at connectErrorNT (net.js:1020:8)
at _combinedTickCallback (internal/process/next_tick.js:74:11)
at process._tickDomainCallback (internal/process/next_tick.js:122:9)
I am calling the function in the firebase auth trigger when a user is created as below:
exports.createUser = functions.auth.user().onCreate(event => {
if (event.data.photoURL) {
utils.downloadImageFromUrl(event.data.photoURL)
.then(function(res){
console.log("User Photo", res);
})
.catch(function(error){
console.log("Error", error);
})
}
});
Any help would be greatly appreciated.
Not entirely sure yet if this is the answer, but after reading the documentation, I read their free plan which says you cannot make any out bound requests. So I guess getting an image from a Url counts as an outbound request. After I start paying for their service, I will come back to verify if this was the problem.

Resources