sending JSON from node js to jquery client but it cannot - javascript

I try to send JSON data to client. I test typeof dataJ and it return object at console dataJ is printed dataJ=[object Object],[object Object]. At client, it displays nothing and it alert XMLHttpRequest.responseText is null and textStatus is error messages and errorThrown is null. Since it doesn't say error, I don't know what does I do wrong.
server site:
app.post('/myaction', async function (req, res) {
async function next_func(req, res) {
var myJson = await show();
return myJson;
}
dataJ = await next_func(req, res);
console.log("dataJ=" + dataJ);
console.log(typeof dataJ)
res.status(200);
res.contentType('application/json');
res.send(dataJ);
});
app.listen(8081, function () {
console.log('Server running at http://127.0.0.1:8081/');
});
async function show() {
var con = mysql.createConnection({
host: "127.0.0.1",
user: "root",
password: "aaaaaaaa",
database: "doto"
});
var sql = "select * from task_list";
resultsArray = [];
await new Promise((resolve, reject) => {
con.connect((err, connection) => {
if (err) return reject(err)
con.query(sql, (err, rows, fields) => {
if (err) return reject(err)
resolve(rows.forEach((row) => {
resultsArray.push({
detail: row.details,
status: row.status,
subject: row.subject
});
})
)
})
})
})
console.log("resultsArray" + resultsArray);
return resultsArray;
}
client site:
$.fn.ajaxShow = function (st) {
xhrct = $.ajax({
type: 'POST',,
data: {
status: st
},
url: 'http://127.0.0.1:8081/myaction',
success: function (data) {
alert("function");
$('#tb').empty();
if (data != null) {
var fotoData = $.parseJSON(data);
$(fotoData).each(function (i, obx) {
alert("fotoData");
$('#tb').append('<tr>')
.append('<td>' + obx.detail + '</td>')
.append('<td>' + obx.status + '</td>')
.append('<td>' + obx.subject + '</td>')
.append('</tr>');
});
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("XMLHttpRequest: " + XMLHttpRequest.responseText);
alert("textStatus: " + textStatus);
alert("errorThrown: " + errorThrown);
}
});
}

Related

refresh page on function call javascript

I have a script where I am uploading a file to cloudinary, and then when it uploads, call my nodejs function (through js on front-end) and then update the file in my db. its working, but when I call the function, it does not render the page again. Instead nothing happens, but my db updates:
front-end script:
<script src="https://widget.cloudinary.com/v2.0/global/all.js" type="text/javascript"></script>
<script type="text/javascript">
var myWidget = cloudinary.createUploadWidget({
cloudName: 'ps',
uploadPreset: 'ld3l7evv'}, (error, result) => {
if (!error && result && result.event === "success") {
console.log('Done! Here is the image info: ', result.info);
console.log(result.info.secure_url)
var result_url = result.info.secure_url;
console.log("result url is " + result_url)
document.getElementById("url").value = result_url;
var employee_num = document.getElementById('employee_num').value
fetch('/changeProfileImage', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
result_url,
employee_num
})
})
}
}
)
backend (node.js):
app.post('/changeProfileImage', (req, res) => {
var employee_num = req.body.employee_num;
var url = req.body.result_url;
console.log("e " + employee_num)
console.log("u " + url)
var changeProfileImage = "update EMPLOYEES set (PROFILE_IMAGE)= '" + url + "' where EMPLOYEE_NUM = '" + employee_num + "'";
ibmdb.open(ibmdbconnMaster, function (err, conn) {
if (err) return console.log(err);
conn.query(changeProfileImage, function (err, rows) {
if (err) {
console.log(err);
}
console.log("succes")
conn.close(function () {
// console.log("closed the function /index");
});
})
})
})
but it is not actually refreshing / reloading the page after it updates the db. any idea?

How to get all the emails sent to and received from an email Id?

I'm trying to implement node-imap and I need to get all the emails received from and sent to an email id.
I've been able to use https://developers.google.com/oauthplayground to generate a refresh token but it expires in an hour so I need a method to generate it directly from the code and In the search request response I'm not getting any message subject or anything.
let Imap = require("imap"),
inspect = require("util").inspect,
config = require('lt-config'),
xoauth2 = require("xoauth2"),
xoauth2gen,imap;
xoauth2gen = xoauth2.createXOAuth2Generator({
user: "mymailid",
clientId: config.MAIL_GOOGLE_CLIENT_ID,
clientSecret: config.MAIL_GOOGLE_CLIENT_SECRET,
refreshToken: config.MAIL_REFRESH_TOKEN,
accessToken: config.MAIL_ACCESS_TOKEN
});
function getAuthorizedImap() {
return new Promise((resolve, reject) => {
xoauth2gen.getToken(function(err, token) {
if (err) {
return console.log(err);
}
console.log("AUTH XOAUTH2 " + token);
config.xoauth2 = token;
imap = new Imap({
user: "test#example.com",
xoauth2: token,
host: "imap.gmail.com",
port: 993,
tls: true
});
imap.once("ready", function() {
resolve(imap);
});
imap.once("error", function(err) {
console.log(err);
});
imap.once("end", function() {
console.log("Connection ended");
});
imap.connect();
});
setTimeout(() => reject('Timeout get token process'), 6000);
})
}
function filterMails(emailId) {
return new Promise(async resolve => {
try {
imap = await getAuthorizedImap();
openInbox(function(err, box) {
if (err) throw err;
imap.search([ ['HEADER', 'FROM', emailId] ], function(err, results) {
if (err) throw err;
console.log("results", results);
var f = imap.fetch(results, { bodies: "HEADER.FIELDS (FROM TO SUBJECT DATE)" });
f.on("message", function(msg, seqno) {
console.log("Message #%d", seqno);
var prefix = "(#" + seqno + ") ";
msg.on("body", function(stream, info) {
console.log(prefix + "Body");
console.log("Body received", info);
});
msg.once("attributes", function(attrs) {
console.log(
prefix + "Attributes: %s",
inspect(attrs, false, 8)
);
});
msg.once("end", function() {
console.log(prefix + "Finished");
});
});
f.once("error", function(err) {
console.log("Fetch error: " + err);
});
f.once("end", function() {
console.log("Done fetching all messages!");
imap.end();
});
});
});
} catch(e) {
console.log("Errror while getting emails from GMAIL ====>>", e);
}
});
}
function openInbox(cb) {
imap.openBox("INBOX", true, cb);
}
module.exports = filterMails;
I want a JSON response from search and to generate a refresh token dynamically. Any help will be appericiated.

NodeJS Async Database fetch server freezing

I have an application running on NodeJS(express + mongoose + jade).
I have a post-route /search (all routes are in a separate module) which should handle fetching data from mongo database and inserting it into jade template(in this case just printing th console):
router.post('/search', function (req,res) {
var componentsArray = null;
function getArray(){
console.log('Initializing...');
componentsArray = dataExchanger.search(req.body.select, req.body.selectType, req.body.searchField);
}
getArray(function () {
console.log('Documents returned.');
console.log('Printing array...');
console.log('Array: ' + componentsArray);
console.log('Array type: ' + typeof (componentsArray));
console.log('Rendering page...');
res.render('search_results');
});
});
Searching and fetching function implemented in a different module dataExchanger:
exports.search = function(select, type, data) {
console.log('Fetching documents...');
componentsModel.find({name: data}, function (err, docs) {
if(!err) {
console.log('Returning documents...');
return docs;
} else {
console.log('Can\'t return documents!');
throw err;
}
});
};
The problem is that when I am using a callback function for getArray(), the server just freezes at the moment of returning docs and stops responding.
What am I doing wrong?
Try to use async/await
router.post('/search', async (req,res) => {
let componentsArray;
try {
componentsArray = await dataExchanger.search(req.body.select, req.body.selectType, req.body.searchField);
} catch(e){
//If error in request and no data.
console.error('Error', e.message);
return res.render('error_message');
}
console.log('Documents returned.');
console.log('Printing array...');
console.log('Array: ' + componentsArray);
console.log('Array type: ' + typeof (componentsArray));
console.log('Rendering page...');
res.render('search_results');
});
And here is your dataExchanger
exports.search = function(select, type, data) {
console.log('Fetching documents...');
return new Promise((resolve, reject) => {
componentsModel.find({name: data}, function (err, docs) {
if(err) return reject(err);
resolve(docs);
});
})
};
Further reading: promises, async/await
router.post('/search', function (req,res) {
var componentsArray = null;
function getArray(cb){
console.log('Initializing...');
componentsArray = dataExchanger.search(req.body.select, req.body.selectType, req.body.searchField);
//Execute the callback
cb();
}
getArray(function () {
console.log('Documents returned.');
console.log('Printing array...');
console.log('Array: ' + componentsArray);
console.log('Array type: ' + typeof (componentsArray));
console.log('Rendering page...');
res.render('search_results');
});
});
Looks like your search method is async as well, so you will need to pass the callback down to that to get the desired result.

nested Async not executing as expected

I am new to node js and I am trying to use async module to eliminate the setTimeouts. Here I am facing a problem. It is not working as expected. It calls the second function even before the first function completes execution. I searched for answers and tried multiple ways. But it doesn't seem to work. It prints "Inside db insert in async series" even before the async.forEach finishes. Can anyone please check the code and tell me where I'm going wrong?
setTimeout(function() {
async.series([function(callback1) {
console.log("Inside async series");
try {
var msg = "";
var datas = [];
for (var i = 0; i < service_name.length; i++) {
console.log("Inside for loop service names");
var child = {
"space_guid": space_guid,
"name": service_name[i],
"service_plan_guid": service_plan_guid[i]
};
datas.push(child);
console.log("datas array===" + JSON.stringify(datas))
}
async.forEach(datas, function(data1, callback) {
console.log("Inside async task");
var data = JSON.stringify(data1);
console.log("data value===" + JSON.stringify(data));
var options = {
host: 'api.ng.bluemix.net',
path: '/v2/service_instances' +
'?accepts_incomplete=true',
method: 'POST',
headers: {
'Authorization': full_token_new
}
};
console.log("options is" + JSON.stringify(options));
var reqst = http.request(options, function(res) {
console.log("Sent for request");
res.setEncoding('utf8');
res.on('data', function(chunk) {
msg += chunk;
});
res.on('end', function() {
try {
console.log("message =======", msg);
console.log("-----------------------------------------");
msg = JSON.stringify(msg);
msg1 = JSON.parse(msg);
console.log("printing msg--" + msg1);
console.log("-----------------------------------------");
console.log("here i am", i);
console.log(service_name.length - 1);
callback();
} catch (err) {
console.log(err);
}
});
});
reqst.on('error', function(e) {
console.log(e);
});
reqst.write(data);
reqst.end();
}, function(err) {
console.log("for each error" + err);
});
callback1(null, null);
} catch (err) {
console.log(err);
}
},
function(callback1) {
console.log("Inside db insert in async series")
db_insert(service_name, solnName, full_token_new, uname, version);
callback1(null, null);
}
],
function(err, results) {
if (err) {
console.log("There's an error" + err);
} else {
console.log("result of async", results);
}
})
}, 3000)
You are mixing try...catch with asynchronous code, this is bad practice and almost impossible to do right.
Also, your error stem from the fact you are calling callback just after async.forEach, which don't finish, and go to the next step.
Also, what do you mean by "eliminate the timeout"? Your whole code is in it, you can remove it whenever you want.
'use strict';
async.series([
(callback) => {
let msg = "",
datas = [],
i = 0;
while(i < service_name.length) {
let child = {
"space_guid": space_guid,
"name": service_name[i],
"service_plan_guid": service_plan_guid[i]
};
datas.push(child);
i = i + 1;
}
async.forEach(datas, (data1, callback) => {
let data = JSON.stringify(data1),
options = {
host: 'api.ng.bluemix.net',
path: '/v2/service_instances?accepts_incomplete=true',
method: 'POST',
headers: {
'Authorization': full_token_new
}
},
reqst = http.request(options, (res) => {
res.setEncoding('utf8');
res.on('data', (chunk) => {
msg += chunk;
});
res.on('end', () => {
msg = JSON.stringify(msg);
msg1 = JSON.parse(msg);
callback();
});
});
reqst.on('error', (error) => {
callback(error);
});
reqst.write(data);
reqst.end();
}, (error) => {
callback(error);
});
},
(callback) => {
db_insert(service_name, solnName, full_token_new, uname, version);
callback();
}
],
(error, results) => {
if (error) {
console.log("There's an error" + error);
} else {
console.log("result of async", results);
}
});
Since this smell heavily like a plssendzecode question, I've removed every console.log and gone ES6 to make sure you will not be able to use it as such and need to read the change I made.
I simplify code a little.
datas and processData aren't good names.
setTimeout(onTimer, 3000);
function onTimer() {
var datas = service_name.map(function(name, i) {
return {
space_guid: space_guid,
name: name,
service_plan_guid: service_plan_guid[i]
}
});
function processData(data, callback) {
var options = {
host: 'api.ng.bluemix.net',
path: '/v2/service_instances?accepts_incomplete=true',
method: 'POST',
headers: {
'Authorization': full_token_new
}
};
var reqst = http.request(options, function(res) {
var msg = '';
res.setEncoding('utf8');
res.on('data', function(chunk) {
msg += chunk;
});
res.on('end', function() {
try {
msg = JSON.parse(msg);
callback(null, msg);
} catch (err) {
callback(err);
}
});
});
reqst.on('error', callback);
reqst.write(JSON.stringify(data));
reqst.end();
}
async.map(datas, processData, function(err, results) {
if (err);
return console.log(err);
// process msg of each request db_insert(...);
});
};

Search in Ldap.js

I am trying to use the search method of Ldap.js in my node.js code. But it doesn't work. Here is my code:
searchFunc : function (){
console.log('inside search');
client.bind('cn=Manager,dc=foo,dc=com', kredito231, function(err) {
if (err) {
console.log(err);
client.unbind();
return;
}
var opts = {
filter: (('Email=*#foo.com'))
} ;
//This search works correct:
//client.search( 'cn=x,ou=users' + ',' + 'dc=foo,dc=com', function(err,res){
//This one doesn't work. But everything is done according api
client.search('dc=foo,dc=com', opts, function(err, res) {
res.on('searchEntry', function(entry) {
console.log('hit');
console.log('entry: ' + JSON.stringify(entry.object));
});
res.on('searchReference', function(referral) {
console.log('referral: ' + referral.uris.join());
});
res.on('error', function(err) {
console.log('searchFailed') ;
console.error('error: ' + err.message);
});
res.on('end', function(result) {
console.log('4') ;
console.log('status: ' + result.status);
});
});
});
}
When I use the search method by with dn name, it returns the correct object with its attributes (res.on('searchEntry', function(entry) part executed, because it can find the record in Ldap). But when I use client.search('dc=foo,dc=com', opts, function(err, res) with opt defined above, it always goes to branch 4: res.on('end', function(result) and never returns an error status of 0.
API documentation of Ldap.
This does not work for dc=foo,dc=com because that entry in the LDAP directory does not have the attribute Email and hence your filter does not match. The entry 'cn=x,ou=users,dc=foo,dc=com' in LDAP directory probably has this attribute which is why it works.
In the following way we can able to search user data
function searchUser() {
var opts = {
filter: '(objectClass=*)', //simple search
// filter: '(&(uid=2)(sn=John))',// and search
// filter: '(|(uid=2)(sn=John)(cn=Smith))', // or search
scope: 'sub',
attributes: ['sn']
};
client.search('ou=users,ou=system', opts, function (err, res) {
if (err) {
console.log("Error in search " + err)
} 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);
});
}
});
}

Categories

Resources