Node js with mongodb Error: Can't set headers after they are sent - mongodb

One time two request send this error display and my server close
I have use this code:
exports.getAllCompany = function (req, res) {
Company.find({}, function (err, record) {
if (err) {
res.json({
type: false,
resultData: "Error occured: " + err
});
} else {
res.json({
type: true,
company: record
});
}
});}
The error message:
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:356:11)
at ServerResponse.header (/app/node_modules/express/lib/response.js:730:10)
at ServerResponse.send (/app/node_modules/express/lib/response.js:170:12)
at ServerResponse.json (/app/node_modules/express/lib/response.js:256:15)
at /app/server/mobile_api/AdminController/dashboard.js:279:17
at Query.<anonymous> (/app/node_modules/mongoose/lib/model.js:3388:16)
at /app/node_modules/kareem/index.js:259:21
at /app/node_modules/kareem/index.js:127:16
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickCallback (internal/process/next_tick.js:104:9)

Finally after a long time to solve the issue. follow my answer who have same issue,
exports.getAllCompany = function (req, res) {
res.writeHead(200, {"Content-Type": "application/json"});
Company.find({}, function (err, record) {
if (err) {
res.end(JSON.stringify({
type: false,
resultData: "Error occured: " + err
}));
} else {
res.end(JSON.stringify({
type: true,
company: record
}));
}
});
}

Most probably you are calling res.send() more than once
sharing the /app/server/mobile_api/AdminController/dashboard.js file would be helpful

Related

"[Function: Error Ctor]" error in console

the first console log is getting logged but the second one isn't
and the catch is catching an error which I do not understand ...
this is my route:
router.post("/buy", JwtAuthenticateToken, async (req, res, next) => {
try {
const entry = new PositionModel(req.body)
console.log("new", entry)
const result = await entry.save()
console.log("saved", result)
} catch (error) {
console.log(error)
next(error)
}
})
this is what gets printed in the console:
new {
_id: 6125514a26fb7d06603b1a5a,
stock: 'Apple Inc',
ticker: 'AAPL',
purchasePrice: 149.62,
shares: 1,
owner: 6124e2a70d195a05f4e480cd
}
[Function: ErrorCtor]
I was passing an error to an error creator in my .post("validate")
probably the dumbest 5 lines of code I have ever written.
post("validate", (error, doc, next) => {
if (error) {
const err = createError(400, error)
next(err)
} else {
next(error)
}
})

ldapjs handling client.search response

I have the below code which is binding to an LDAP server and I want to return the user that I have added "ab" within the "interviewees" group (code taken from ldapjs client api page). I can see I am getting back a response from the server with the expected EventEmitter object. I am expecting to see information about the user when calling logging console.log() on the searchEntry object. I appear to have no searchEntry objects. Is my DN for my user correct? I am currently unsure whether the issue is with my query and I am not getting any data back or whether I am failing to process the response correctly?
const client = ldap.createClient({ url: 'ldap://' + LDAP_SERVER + ':' + LDAP_PORT });
// Connect and bind to the Active Directory.
const connectToClient = async () => {
const secret = LDAP_SECRET_KEY;
return await new Promise((resolve, reject) => {
client.bind(LDAP_USER, secret, function (err, res) {
if (err) {
console.error(err);
reject('Failed to connect to LDAP server');
} else {
resolve('Connected to LDAP server');
}
});
});
};
onst searchADForUser = async () => {
return await new Promise((resolve, reject) => {
client.search('CN=ab,OU=interviewees,OU=Users,OU=interview,DC=interview,DC=workspace,DC=com', function (err, res) {
if (err) {
console.error(err);
reject('Error searching LDAP server');
} else {
res.on('searchEntry', function (entry) {
console.log('entry: ' + JSON.stringify(entry.object));
});
res.on('searchReference', function (referral) {
console.log('referral: ' + referral.uris.join());
});
res.on('error', function (err) {
console.error('error: ' + err.message);
});
res.on('end', function (result) {
console.log('status: ' + result.status);
});
resolve(res);
}
});
});
};
const handler = async (event) => {
try {
return responses.success(
await connectToClient().then(async function(event) {
console.log(event);
await searchADForUser().then(function(event) {
console.log(event);
}).catch(function(event) {
console.log(event);
})
}).catch(function(event) {
console.log(event);
})
);
} catch (err) {
console.error(err);
return responses.error(err);
} finally {
client.unbind();
}
};
The active directory structure is below
The central issue I was having was understanding how to process the returned EventEmitter object from the search function. I need to add to an array on each searchEntry event and then return that entry in my resolve callback function only once the end event had occurred. The code above was calling resolve immediately and hence no searchEntry events or the end event had been processed yet.
Code I am now using below:
function (err, res) {
if (err) {
console.error(err);
reject(new Error('Error retrieving users from Active Directory'));
} else {
const entries = [];
res.on('searchEntry', function (entry) {
entries.push(entry);
});
res.on('searchReference', function (referral) {
console.log('referral: ' + referral.uris.join());
});
res.on('error', function (err) {
console.error('error: ' + err.message);
});
res.on('end', function (result) {
console.log('status: ' + result.status);
if (result.status !== 0) {
reject(new Error('Error code received from Active Directory'));
} else {
resolve(entries);
}
});
}
}

Store collection value to variable

I am having issues storing a value in mongodb to a variable to use within my webpage.
When the user fills out a form on my website, I am trying to figure out what the arrivalTrailer was when the user filled out the arrival form.
So far I have
function previousLoad(loadNumber, callback){
CheckCall.find({loadNumber: loadNumber}).sort({date: 'desc'}).limit(1), function(err, arrival){
if (err){
callback(err, null);
}
else {
callback(null, arrival[0]);
}
}};
previousLoad(loadNumber, function(err, arrival){
if (err){
console.log(err);
}
else{
arrivalTrailer = arrival;
console.log(arrival);
}
});
console.log(previousLoad.arrival);
console.log(arrivalTrailer);
Both output as undefined when I try to console.log the variables.
Thank you :D
Try this :
async function previousLoad(loadNumber) {
try {
let resp = await CheckCall.find({ loadNumber: loadNumber }).sort({ date: -1 }).limit(1)
return resp[0]
} catch (error) {
console.log('error ::', error)
throw new Error (error)
}
}
/** You can return response from previousLoad but to test it, Call it from here */
previousLoad(loadNumber).then(resp => { console.log('successfully found ::', resp)}).catch(err => { console.log('Error in DB Op ::', err)});

Tez Payment Request API

I'm trying to integrate Google-Tez payment in my site, But When I'm calling request.show() getting error msg as
"Payee isn't a valid merchant"
, When i call checkCanMakePayment() getting error msg as
"Cannot query payment request"
and I enclose my code below. My UPI ID is "hsbc". Can anyone help me to troubleshoot this issue? and I need to know is there any process like merchant has to register with Google Tez
function onBuyClicked() {
const creditCardPaymentMethod = {
supportedMethods: 'basic-card',
data: {
supportedNetworks: ['visa', 'mastercard'],
supportedTypes: ['credit', 'debit']
}
};
const supportedInstruments = [
{
supportedMethods: ['https://tez.google.com/pay'],
//supportedMethods:[creditCardPaymentMethod],
data: {
pa:'**********',
pn:'**********',
tr:'123456ABCDEFSD',
url:'***********',
mc:'*********',
tn:'Purchase in Merchant'
}
}
];
var details =
{
total:
{
label:'Total',
amount: {
currency:'INR',
value:'10.01' //sample amount
}
},
displayItems: [
{
label:'Original Amount',
amount: {
currency:'INR',
value:'10.01'
}
}
]
};
var request =null;
try {
request = new PaymentRequest(supportedInstruments, details);
console.log(request);
/*request.show()
.then(function(result){
alert("hai");
})
.catch(function(err){
alert('Payment Request Error: '+ err.message+' 74');
});*/
}catch (e) {
alert('Payment Request Error: '+ e.message+'77');
console.log('Payment Request Error: '+ e.message);
//return;
}
if (!request) {
alert('Web payments are not supported in this browser 77');
console.log('Web payments are not supported in this browser.');
// return;
} 
var canMakePaymentPromise = checkCanMakePayment(request);
canMakePaymentPromise
.then(function(result){
showPaymentUI(request,result)
})
.catch(function(err){
console.log('Error in calling checkCanMakePayment: ' + err);
});
}
const canMakePaymentCache = 'canMakePaymentCache';
function checkCanMakePayment(request){
// Checks canMakePayment cache, and use the cache result if it exists.
if(sessionStorage.hasOwnProperty(canMakePaymentCache)){
return Promise.resolve(JSON.parse(sessionStorage[canMakePaymentCache]));
}
// If canMakePayment() isn't available, default to assuming that the method is supported
var canMakePaymentPromise = request.canMakePayment();
if(request.canMakePayment){
canMakePaymentPromise = request.canMakePayment();
}
return canMakePaymentPromise
.then(function(result){
sessionStorage[canMakePaymentCache] = result;
return result;
})
.catch(function (err){
alert('Error calling canMakePayment: '+ err);
console.log('Error calling canMakePayment: '+ err);
});
}
function showPaymentUI(request, canMakePayment){
if(!canMakePayment){
handleNotReadyToPay();
return;
}
// Set payment timeout.
var paymentTimeout = window.setTimeout(function(){
window.clearTimeout(paymentTimeout);
request.abort()
.then(function(){
alert('Payment timed out after 20 mins 129');
console.log('Payment timed out after 20 mins');
}).catch(function(){
alert('Unable to abort,user is in process of paying 132');
console.log('Unable to abort,user is in process of paying');
});
}, 20 * 60 * 1000);
request.show()
.then(function(paymentResponse){
window.clearTimeout(paymentTimeout);
alert("Request Success");
console.log(paymentResponse);
processResponse(paymentResponse); // Handle response from browser
})
.catch(function (err){
alert(err +'142');
console.log(err);
});
}
function handleNotReadyToPay(){
alert("Tez is not ready to handle 149");
}
function processResponse(paymentResponse){
var paymentResponseString = paymentResponseToJsonString(paymentResponse);
console.log(paymentResponseString);
/* fetch('/buy',{
method: 'POST',
headers: new Headers({'Content-Type':'application/json'}),
body:paymentResponseString
})
.then(function(buyResult){
console.log('Buy Result'+buyResult);
})
.catch(function(err){
console.log('Unable to process payment. '+err);
});*/
}
onBuyClicked();
"Payee isn't a valid merchant" error comes when you use customer VPA in place of merchant VPA in the 'pa' field.
Resolution:
Use VPA which is issued for the merchant.

Convert Http Response to Json object Ionic 3

The below response is returned upon calling the signup function
Response {_body: "string(85) "{"message":"A customer with the same email
already exists in an associated website."}"↵", status: 200, ok: true,
statusText: "OK", headers: Headers, …}
headers: Headers {_headers: Map(1), _normalizedNames: Map(1)}
ok: true
status: 200
statusText: "OK"
type: 2
url: "http://127.0.0.1/sandbox/M2API/signup/signup"
_body: "string(85) "{"message":"A customer with the same email already exists in an associated website."}"↵"
__proto__: Body
Signup Function:
signup() {
this.authServiceProvider.postData(this.userData, "signup").then((result) => {
this.responseData = result;
console.log(this.responseData);
if( (JSON.stringify(this.responseData._body)) != "" ) {
this.navCtrl.setRoot(HomePage);
} else {
console.log("User already exists");
}
}, (err) => {
//connection failed error message
console.log("something went wrong");
});
}
When i do console.log(JSON.stringify(this.responseData)); backslahes are added to json object
How to avoid that and access message in the response.
Use this
import 'rxjs/add/operator/map';
this.http.get('YOUR_API_ENDPOINT').map(res => res.json()).subscribe(data => {
console.log(data);
});