How do I see the request body with node-soap - node.js

I have some sample code that looks like the following:
var soap = require('soap');
var url = "http://www.example.com?wsdl";
var soapHeader = "<AuthHeader>...</AuthHeader>";
soap.createClient(url, function(err, client){
client.addSoapHeader(soapHeader);
var args = {
'arg1': 1
}
};
client.SomeMethod(args, function(err, result){
if(err){
throw err;
}
console.log(JSON.stringify(result));
});
});
The problem is the request is failing due to either an incorrect header or arguments I'm passing. It would be much easier to debug if I could see the entirety of the request body. How is that done?

Not sure if this is still relevant to you, but here goes:
var soap = require('soap');
var url = "http://www.example.com?wsdl";
var soapHeader = "<AuthHeader>...</AuthHeader>";
soap.createClient(url, function(err, client){
client.addSoapHeader(soapHeader);
var args = {
'arg1': 1
}
};
client.SomeMethod(args, function(err, result){
if(err){
throw err;
}
console.log('last request: ', client.lastRequest);
console.log(JSON.stringify(result));
});
});
The extra console.log statement with "lastRequest" will show the XML request that is being sent, which can be used for debugging. Hope this helps.

Related

Cannot set headers after they are sent to clients in node.js

My code is not working . I am beginner and don't know my problem. Kindly help.I have seen one or two solution on stackoverflow but didnot get .
This is code.
app.post('/post',(request,response)=>{
var description=request.body.description;
var contact_number=request.body.contact_number;
var city=request.body.city;
var budget=request.body.budget;
var category=request.body.optradio;
var query=connection.query("insert into jobs(Jobs_id,Description,Category,City,Contact_number,Budget) values(?,?,?,?,?,?)",[null,description,category,city,contact_number,budget],function(err){
if(err)
console.log(err);
else
response.send("successful");
});
response.redirect('/data');
});
app.get('/data',function(request,response){
connection.query("SELECT * FROM jobs ORDER BY Jobs_id DESC",(err, rows,fields) => {
if(err) {
console.log(err);
}
else {
response.render('feed', {title : 'Jobs Details',
items: rows })
}
});
});
app.listen(3000);
This is the error
pp.post('/post', (request, response) => {
var description = request.body.description;
var contact_number = request.body.contact_number;
var city = request.body.city;
var budget = request.body.budget;
var category = request.body.optradio;
var query = connection.query("insert into jobs(Jobs_id,Description,Category,City,Contact_number,Budget) values(?,?,?,?,?,?)", [null, description, category, city, contact_number, budget],
function (err) {
if (err) {
console.log(err);
} else {
response.redirect('/data');
}
});
});
app.get('/data', function (request, response) {
connection.query("SELECT * FROM jobs ORDER BY Jobs_id DESC", (err, rows, fields) => {
if (err) {
console.log(err);
}
else {
response.render('feed', {
title: 'Jobs Details',
items: rows
})
}
});
});
app.listen(3000);
There can be only one response to single HTTP request. In your code, you are first trying to send response with
response.send("successful");
but this on its own doesn't break the flow of the function which means that if the condition is actually met then this will execute and the execution continues and finds another response, in this case
response.redirect('/data');
and it will try to send another response to the original http request but at this point it is already too late because one response has already been send.
To solve this issue in general, you can place return in front of any line of code that is closing the the connection (response.send, response.redirect, ...). That way, the function's execution is terminated at the first response, whichever it is.
So you could do something like
var query=connection.query("insert into jobs(Jobs_id,Description,Category,City,Contact_number,Budget) values(?,?,?,?,?,?)",[null,description,category,city,contact_number,budget],function(err){
if(err)
console.log(err);
else
return response.send("successful");
});
return response.redirect('/data');
});

How to send response to front end after execution of mongodb request?

I am creating sign up page. Where, I first check whether user email already present in our mongodb database or not. If it is present then I want to send error message to frontEnd. However, I am failing to do that, I think it might be because of asynchronous behavior of JavaScript.My Code is as following:
var myObj , myJSON
var SignUpUserEmail, SignUpUserPassword, SignUpUserName, SignUpErr
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
var q = url.parse(req.url, true).query
SignUpUserEmail = q.SignUpUserEmail
SignUpUserPassword = q.SignUpUserPassword
SignUpUserName = q.SignUpUserName
MongoClient.connect("mongodb://localhost:27017/ABC",function(err,
database) {
if (err) throw err;
var db=database.db('ABC')
let findOneParam = {"UserEmail":SignUpUserEmail}
db.collection('Profiles').findOne(findOneParam, function(err, result) {
if (err) throw err;
if(!result) {
db.collection('Profiles', function(err, collection){
if (err) throw err;
collection.insertOne({"UserId":"ProfileA0001",
"UserEmail":SignUpUserEmail,
"UserPassword":SignUpUserPassword,
"UserName":SignUpUserName,
"IsEmailAuthenticated":"false"
}, function(err, res){
if (err) throw err;
SignUpErr = "document inserted"
console.log("SignUpErr inside:", SignUpErr)
})
})
} else {
SignUpErr = "Email already has been registered."
console.log("SignUpErr inside:", SignUpErr)
}
})
})
console.log("SignUpErr outside:", SignUpErr)
myObj = {"SignUpErr":SignUpErr};
myJSON = JSON.stringify(myObj);
res.end(myJSON);
}).listen(9000);
Note: "SignUpErr inside:" giving correct result. however, "SignUpErr outside:" shows it as undefined.
Note: "SignUpErr inside:" giving correct result. however, "SignUpErr outside:" shows it as undefined.
This is because of the asynchronous nature of the nodejs. SignUpErr will be undefined until the time it is initialized within the db.collection('Profiles',function(){}) call.
So, to fix this, you need to send response within db.collection('Profiles',function(){}). that's, after the initilization.
Making those changes to your code,
'use strict';
const http = require('http');
http.createServer(function (req, res) {
res.statusCode = 200; // Setting the status code
res.setHeader('Content-Type', 'text/plain'); // Setting the content-type for response
let {SignUpUserEmail, SignUpUserPassword, SignUpUserName} = url.parse(req.url, true).query;
MongoClient.connect("mongodb://localhost:27017/ABC", function (err, database) {
if (err) {
throw err;
}
let db = database.db('ABC');
db.collection('Profiles').findOne({
UserEmail: SignUpUserEmail
}, function (err, result) {
if (err) {
throw err
}
if (result) {
let msg = "Email already has been registered.";
console.log("SignUpErr inside:", msg);
return res.end(JSON.stringify({
SignUpErr: "document inserted"
}));
}
db.collection('Profiles', function (err, collection) {
if (err) throw err;
collection.insertOne({
"UserId": "ProfileA0001",
"UserEmail": SignUpUserEmail,
"UserPassword": SignUpUserPassword,
"UserName": SignUpUserName,
"IsEmailAuthenticated": "false"
}, function (err, dbresult) {
if (err) {
throw err;
}
let msg = "document inserted";
console.log("SignUpErr inside:", msg);
return res.end(JSON.stringify({
SignUpErr: "document inserted"
}));
})
});
});
});
}).listen(9000);
I usually use express as my web framework which comes with res.send() method, where you can send your response . I usually build a JSON response, and send it as res.send(JSON.stringify(data)); There is also res.JSON(data).
If you wish to use HTTP module , then you can use res.end() method.
Details are provided here . Hope this helps.

Node - Simple xml API Request

I'm using the latest node.js (and express) to make an API call to a site that returns... XML... Ugh >_>.
I've scowered the web and found a million different ways, but I don't know the latest, most up to date / best way to make a request and get a response in node/express.
I tried using https://github.com/request/request and did the following:
var sendJsonResponse = function(res, status, content) {
res.status(status);
res.json(content);
};
var token = request
.get('some-website.com/api/stuff')
.on('response', function(response) {
console.log(response.statusCode);
console.log(response.headers['content-type']);
});
sendJsonResponse(res, 200, token);
in the console.log statements I get 200 and then application/xml;charset=utf-8.
But on my page I don't get the xml I'm looking for. Any ideas? I've tried using https://github.com/Leonidas-from-XIV/node-xml2js to attempt to "parse" the response, in case node just can't handle the xml response, but to no avail.
var xml2js = require('xml2js');
parser.parseString(response, function(err, result) {
console.dir(result);
console.log('Done');
});
Any help on accessing an API using Node and actually using the XML response, please?
EDIT ANSWER
For the Node.js request and xml parsing of the returned xml content:
var request = require('request');
var xml2js = require('xml2js');
var sendJsonResponse = function(res, status, content) {
res.status(status);
res.json(content);
};
/* GET XML Content*/
module.exports.dsRequest = function(req, res) {
var parser = new xml2js.Parser();
request('url_for_xml_request', function(error, response, body) {
parser.parseString(body, function(err, result) {
sendJsonResponse(res, 200, result);
});
});
};
I think this will work, because request is async, you should write like below:
var sendJsonResponse = function(res, status, content) {
res.status(status);
res.json(content);
};
request.get('http://some-website.com/api/stuff', function (err,response, body) {
sendJsonResponse(res, 200, body);
});

Empty body in a response when using request

I have the following code:
var request = require('request');
var cheerio = require('cheerio');
var URL = require('url')
var fs = require('fs')
fs.readFile("urls.txt", 'utf8', function(err, data) {
if (err) throw err;
var urls = data.split('\n');
urls = urls.filter(function(n){return n});
for(var i in urls) {
request(urls[i], function(err, resp, body) {
if (err)
throw err;
$ = cheerio.load(body,{lowerCaseTags: true, xmlMode: true});
$('item').each(function(){
console.log("----------");
console.log($(this).find('title').text());
console.log($(this).find('link').text());
console.log($(this).find('pubDate').text());
});
}).end();
}
});
and from the urls.txt file I only have the following url:
http://www.visir.is/section/?Template=rss&mime=xml
When I use wget on that url I get a response which looks like an rss feed but when I do it in the code above the body is empty. Can someone explain to me why and how can I fix this?
Update: Simply removing .end() from your original script works. end() terminates the script on callback. IMO, in 2016, I'd definitely choose Request over Needle.
Request is an odd bird, and why it's not working in your case it's giving no information in the response at all.
Try with Needle instead:
var needle = require('needle');
var cheerio = require('cheerio');
var URL = require('url')
var fs = require('fs')
fs.readFile("urls.txt", 'utf8', function(err, data) {
if (err) throw err;
var urls = data.split('\n');
urls = urls.filter(function(n){return n});
for(var i in urls) {
needle.get(urls[i], function(err, resp, body) {
if (err)
throw err;
$ = cheerio.load(body,{lowerCaseTags: true, xmlMode: true});
$('item').each(function(){
console.log("----------");
console.log($(this).find('title').text());
console.log($(this).find('link').text());
console.log($(this).find('pubDate').text());
});
});
}
});

Can't access postgres database, query doesn't seem to work

var client = new pg.Client(clientConfig);
var queryConfig = {text: 'SELECT messageID FROM privateMessages WHERE message = $1',
values: ['test']};
var server = http.createServer(function(request, response) {
client.connect();
response.writeHead(200, {'content-type': 'text/html'});
client.query(queryConfig, function(err, result) {
if (err){
console.log("error");
}
response.end('You are visitor number');
});
client.end();
});
server.listen(3001)
The query being made is valid. But the callback function doesn't seem to work. Why isn't the database being accessed? This has been tried with insertions.

Resources