why is the request post not running - javascript

I am currently encountering some issues where request.post() is not running. Somehow my code is skipping both the request.post() in the if and else statements. Could anyone advise what I did wrong or how to improve my code? It would great if someone also explains to me what I did wrong.
CurrentOrder.findOneAndUpdate(_id, orderBody, function (err, data) {
if (err) return next(err)
CurrentOrder.findOne(_id2, function(err, order) {
if (err) return next(err)
if(order.canadaTrackingStatus.length == 1 && orderBody.paymentStatus == 'paid'){
order.canadaTrackingStatus = [order.canadaTrackingStatus[0], {date: new Date(), status: '门店已揽收'}];
order.save(function(err) {
if (err) return next(err)
var modItems = merge_items(order.items)
var url = {OrderCode:order.orderNumericCode,Sender:{Name:order.senderName,Tel:order.senderPhone,ProvinceName:order.senderProvince,CityName:order.senderCity,ExpAreaName:order.senderCity,Address:order.senderAddress},Receiver:{Name:order.recipientName,Tel:order.recipientPhone,ProvinceName:order.recipientProvince,CityName:order.recipientCity,ExpAreaName:order.recipientCity,Address:order.recipientAddress},Content:modItems}
var newurl = encodeURI(JSON.stringify(url))
console.log(newurl)
request.post({
headers: { 'Content-Type':'content=text/html;charset=utf-8' },
url : `http://rrr.cn/order/create?EBusinessID=1afs190&AppKey=trytr5fasfasf68980hg23gff&Sign=a1a4e30c83c8c9e6d6fd1fasfasfac55dbc1f2f&RequestType=100232&RequestData=${newurl}`
},function(error,response,body){
var chinacode = JSON.parse(body).logisticcode
var newbody = Object.assign(order, {vipOrderNumericCode : chinacode})
CurrentOrder.findOneAndUpdate({_id:order._id}, newbody, function (err, data2) {
if(err) return next(err)
console.log('if')
})
})
});
}else if(order.canadaTrackingStatus.length == 1 && orderBody.paymentStatus == 'pending'){
order.canadaTrackingStatus = [order.canadaTrackingStatus[0]];
order.save(function(err) {
if (err) return next(err)
var modItems = merge_items(order.items)
var url = {OrderCode:order.orderNumericCode,Sender:{Name:order.senderName,Tel:order.senderPhone,ProvinceName:order.senderProvince,CityName:order.senderCity,ExpAreaName:order.senderCity,Address:order.senderAddress},Receiver:{Name:order.recipientName,Tel:order.recipientPhone,ProvinceName:order.recipientProvince,CityName:order.recipientCity,ExpAreaName:order.recipientCity,Address:order.recipientAddress},Content:modItems}
var newurl = encodeURI(JSON.stringify(url))
console.log(newurl)
request.post({
headers: { 'Content-Type':'content=text/html;charset=utf-8' },
url : `http://rrr.cn/order/create?EBusinessID=11987650&AppKey=trytr56809876980hg23gff&Sign=a1a4e30c83c8c9e6d6fd10987ac55dbc1f2f&RequestType=1002&RequestData=${newurl}`
},function(error,response,body){
var chinacode = JSON.parse(body).logisticcode
var newbody = Object.assign(order, {vipOrderNumericCode : chinacode})
CurrentOrder.findOneAndUpdate({_id:order._id}, newbody, function (err, data2) {
if(err) return next(err)
console.log('else')
})
})
});
}
});
if (req.user.userRole == 'admin') {
if (data.batch) res.redirect('/admin/view-batches')
else res.redirect('/admin/orders')
} else {
return res.redirect('/client/current')
}
})

Related

DB query is returning undefined value in node.js with oracledb

i am new to node.js and javascript and trying to learn the things. in my tests i need to pick a value from Oracle DB through select query and need to use it in to my code later. i am referring the same code given on https://blogs.oracle.com/opal/entry/introducing_node_oracledb_a_node and it is working fine but am not able to return the result value.
below is my code :
this.getTableData = function(){
var res;
oracledb.getConnection(
{
user : "user",
password : "password",
connectString : "db "
},
function (err, connection) {
if (err) {
console.error(err);
console.log("errorrrrrrrrrrr : "+err);
return;
}
connection.execute("SELECT query",
function(err, result) {
if (err) {
console.error(err);
return;
}
else if(result) {
res = result.rows[0][0];
console.log("result in else if: "+res);
return res;
}});
});
};
the function returns undefined value.
Of course it returns undefined. It's because of async callback functions. You'll need to do something like this:
this.getTableData = function(callback){
oracledb.getConnection(
{
user : "user",
password : "password",
connectString : "db "
},
function (err, connection) {
if (err) {
console.error(err);
console.log("errorrrrrrrrrrr : "+err);
return;
}
connection.execute("SELECT query",
function(err, result) {
if (err) {
console.error(err);
return;
}
else if(result) {
var res = result.rows[0][0];
console.log("result in else if: "+res);
callback(res);
}});
});
};
getTableData(function (result) {
console.log(result);
});
The other way you could solve this problem is using a Promise:
this.getTableData = function () {
return new Promise(function (resolve, reject) {
oracledb.getConnection(
{
user: "user",
password: "password",
connectString: "db "
},
function (err, connection) {
if (err) {
console.error(err);
reject(err);
console.log("errorrrrrrrrrrr : " + err);
return;
}
connection.execute("SELECT query",
function (err, result) {
if (err) {
console.error(err);
reject(err);
return;
}
else if (result) {
var res = result.rows[0][0];
console.log("result in else if: " + res);
resolve(res);
}
});
});
});
};
getTableData()
.then(function (result) {
console.log(result);
});
The code you've asked for in your comment:
var AddPage = function () {
var self = this;
this.enterOtpInput = element(by.model("beneDetail.otp"));
this.enterMpinInput = element(by.model("retailerMpin"));
this.verifyBeneficiaryButton = element(by.xpath("//div[2]/div/button"));
this.verifyBene = function () {
support.getTableData()
.then(function (result) {
console.log("adam: " + result);
self.enterOtpInput.sendKeys(result);
self.enterMpinInput.sendKeys("1111");
self.verifyBeneficiaryButton.click();
});
};
}

Change async workflow to Promise (Bluebird)

I have been trying to wrap my head around Promises. For basic concepts I understand, but once it gets nested, I am a little bit confused. Any feedback is appreciated
Here is the code that I am trying to refactor into Promises (bluebird)
var getIndividualData = function(url, doneGetIndividualData) {
var $, data;
request(url, function(err, res, body) {
if (!err && res.statusCode === 200) {
$ = cheerio.load(body);
data = {
title: $("#itemTitle").children()["0"].next.data,
condition: $("#vi-itm-cond").text(),
price: $("#prcIsum_bidPrice").text(),
imgUrl: $("#icImg")[0].attribs.src,
createdAt: chance.date(),
likes: chance.integer({min: 0, max: 1000})
};
doneGetIndividualData(null, data);
} else {
doneGetIndividualData(err);
}
});
};
var getListing = function(url, doneGetListing) {
var $;
var links = [];
request(url, function(err, res, body) {
if (!err && res.statusCode === 200) {
$ = cheerio.load(body);
$('.vip').each(function(i, el) {
if (i < 15) {
links.push(el.attribs.href);
}
});
async
.concat(links, getIndividualData, function(err, result) {
return doneGetListing(null, result);
});
} else {
doneGetListing(err);
}
});
};
var putToMongo = function(err, result) {
if (devConfig.seedDB) {
mongoose.connect(devConfig.mongo.uri);
Item.find({}).remove(function(err, items) {
Item.create(result, function(err, items) {
console.log('done');
process.kill();
});
});
}
};
async
.concat(urls, getListing, putToMongo);
The first thing to do is wrap request in something that returns a promise. Many promise libraries have utilities for "promisifying" async functions, but I don't think that'll work here because request passes two success values into its callback:
var requestAsync = function(url) {
return new Promise(function (resolve, reject) {
request(function (err, res, body) {
if (err) {
reject(err);
}
resolve({ res: res, body: body});
});
});
};
Once that's done, it gets a lot easier:
var getIndividualData = function(url) {
return requestAsync(url).then(function (result) {
if (result.res.statusCode === 200) {
var $ = cheerio.load(result.body);
return {
title: $("#itemTitle").children()["0"].next.data,
condition: $("#vi-itm-cond").text(),
price: $("#prcIsum_bidPrice").text(),
imgUrl: $("#icImg")[0].attribs.src,
createdAt: chance.date(),
likes: chance.integer({min: 0, max: 1000})
};
}
throw new Error("Individual data status code: " + result.res.statusCode);
});
};
var getListing = function(url, doneGetListing) {
return requestAsync(url).then(function (result) {
if (result.res.statusCode === 200) {
var $ = cheerio.load(result.body),
promises = $('.vip').filter(function (i) {
return i < 15;
}).map(function (i, el) {
return getIndividualData(el.attribs.href);
});
return Promise.all(promises);
}
throw new Error("Listing status code: " + result.res.statusCode);
});
};
var putToMongo = function(result) {
if (devConfig.seedDB) {
mongoose.connect(devConfig.mongo.uri);
Item.find({}).remove(function(err, items) {
Item.create(result, function(err, items) {
console.log('done');
process.kill();
});
});
}
};
Promise.all(urls.map(getListing))
.then(putToMongo)
.catch(function (err) {
// handle error
});

How to return value from a series of cascading async code

I need some advice on how to re/write the db specific cascading code (callback) so that I can effectively return a value to the underlying if/else.
I am using restify and the db lib is node-mssql (tedious).
function authenticate(req, res, next) {
var auth = req.authorization;
var err;
if (auth.scheme !== 'Basic' || ! auth.basic.username || ! auth.basic.password) {
authFail(res);
err = false;
} else {
var sql = "SELECT ..."
var connection = new mssql.Connection(config.mssql, function(err) {
if (err) {console.log(err);}
var request = connection.request();
request.query(sql, function(err, recordset) {
if (err) {console.log(err);}
if (recordset.length === 0) {
authFail(res);
err = false; // <--- I need to be able to return this
} else {
authSuccess();
}
});
});
}
next(err);
}
I've reviewed the suggested duplicate, and while I think, I understand the issue, I can't work out the cleanest (lets be honest any) way to get this to work.
How about using Promises?
function authenticate(req, res, next) {
var auth = req.authorization;
if (auth.scheme !== 'Basic' || ! auth.basic.username || ! auth.basic.password) {
authFail(res);
next(false);
} else {
var sql = "SELECT ..."
var connection = new mssql.Connection(config.mssql, function(err) {
if (err) {console.log(err);}
var request = connection.request();
request.query(sql).then(function(recordset) {
if (recordset.length === 0) {
authFail(res);
return false; // <--- return this
} else {
authSuccess();
}
}).catch(function(err) {
console.log(err);
return err;
}).then(function(err) { next(err); });
});
}
}

How can I return out of a node callback to mongo and redirect?

I think I'm getting confused with the callback, but I have the following code, and I'm trying to return newpost_template when the subject name is invalid. I think my logic is correct, but it's not returning. It's passing right through. It works perfectly fine and renders newpost_template when there is !title. Any advice is welcome, thanks.
This works:
if (!title) {
var errors = "Post must contain a title";
return res.render("newpost_template", {
subject: title,
username: req.username,
body: req.body,
tags: req.tags,
errors: errors
});
}
This doesn't work:
users.findAllSubjectNames(title, req.username, res, req, function(err, doc) {
"use strict"
if (err) return next(err);
console.log('doc');
console.log(doc);
if (doc === null) {
console.log('this shows');
var errors = "Subject name already taken!";
console.log('this also shows');
//return res.redirect(" / newpost ")
return res.render("newpost_template ", {
subject: title,
username: req.username,
body: req.body,
tags: req.tags,
errors: errors
});
console.log('this doesnt show');
}
});
this.findAllSubjectNames = function(title, user, res, req, callback) {
"use strict";
users.find({}, {
"teacher.subject ": 1
}).toArray(function(err, result) {
"use strict ";
if (err) return callback(err, null);
console.log('result');
for (var r = 0; r < result.length; r++) {
for (var t = 0; t < result[r].teacher.length; t++) {
if (result[r].teacher[t].subject == title && result[r]._id != user) {
console.log('INVALID!');
return callback(err, null);
//return res.redirect(" / newpost ")
}
}
}
return callback(err, result);
});
}
I got it. I had to put the redirect and res.render in an if else clause so only one would execute and only after doc returned. I also had to separate it into it's own function.
users.findAllSubjectNames(title, req.username, function(err, doc){
"use strict"
if(err) return next(err);
//return res.redirect("/newpost") //res.render("newpost_template", {subject:title, username:req.username, body:req.body, tags:req.tags, errors:errors});
if(doc === null){
var errors = "Subject name already taken!";
return res.render("newpost_template", {subject:title, username:req.username, body:req.body.body, tags:req.tags, errors:errors});
} else {
classNumber(title, req, res, next);
return res.redirect("/profile");
}
});

How to use this node.js module in some file

This is my 3rd party node-js module:
var knox = require('knox')
, Resource = require('deployd/lib/resource')
, httpUtil = require('deployd/lib/util/http')
, formidable = require('formidable')
, fs = require('fs')
, util = require('util')
, path = require('path');
function S3Bucket(name, options) {
Resource.apply(this, arguments);
if (this.config.key && this.config.secret && this.config.bucket) {
this.client = knox.createClient({
key: this.config.key
, secret: this.config.secret
, bucket: this.config.bucket
});
}
}
util.inherits(S3Bucket, Resource);
module.exports = S3Bucket;
S3Bucket.label = "S3 Bucket";
S3Bucket.prototype.clientGeneration = true;
S3Bucket.events = ["upload", "get", "delete"];
S3Bucket.basicDashboard = {
settings: [{
name: 'bucket'
, type: 'string'
}, {
name: 'key'
, type: 'string'
}, {
name: 'secret'
, type: 'string'
}]
};
S3Bucket.prototype.handle = function (ctx, next) {
var req = ctx.req
, bucket = this
, domain = {url: ctx.url};
if (!this.client) return ctx.done("Missing S3 configuration!");
if (req.method === "POST" && !req.internal && req.headers['content-type'].indexOf('multipart/form-data') === 0) {
var form = new formidable.IncomingForm();
var remaining = 0;
var files = [];
var error;
var uploadedFile = function(err) {
if (err) {
error = err;
return ctx.done(err);
} else if (!err) {
remaining--;
if (remaining <= 0) {
if (req.headers.referer) {
httpUtil.redirect(ctx.res, req.headers.referer || '/');
} else {
ctx.done(null, files);
}
}
}
};
form.parse(req)
.on('file', function(name, file) {
remaining++;
if (bucket.events.upload) {
bucket.events.upload.run(ctx, {url: ctx.url, fileSize: file.size, fileName: file.filename}, function(err) {
if (err) return uploadedFile(err);
bucket.uploadFile(file.filename, file.size, file.mime, fs.createReadStream(file.path), uploadedFile);
});
} else {
bucket.uploadFile(file.filename, file.size, file.mime, fs.createReadStream(file.path), uploadedFile);
}
})
.on('error', function(err) {
ctx.done(err);
error = err;
});
req.resume();
return;
}
if (req.method === "POST" || req.method === "PUT") {
domain.fileSize = ctx.req.headers['content-length'];
domain.fileName = path.basename(ctx.url);
if (this.events.upload) {
this.events.upload.run(ctx, domain, function(err) {
if (err) return ctx.done(err);
bucket.upload(ctx, next);
});
} else {
this.upload(ctx, next);
}
} else if (req.method === "GET") {
if (ctx.res.internal) return next(); // This definitely has to be HTTP.
if (this.events.get) {
this.events.get.run(ctx, domain, function(err) {
if (err) return ctx.done(err);
bucket.get(ctx, next);
});
} else {
this.get(ctx, next);
}
} else if (req.method === "DELETE") {
if (this.events['delete']) {
this.events['delete'].run(ctx, domain, function(err) {
if (err) return ctx.done(err);
bucket.del(ctx, next);
});
} else {
this.del(ctx, next);
}
} else {
next();
}
};
S3Bucket.prototype.uploadFile = function(filename, filesize, mime, stream, fn) {
var bucket = this;
var headers = {
'Content-Length': filesize
, 'Content-Type': mime
};
this.client.putStream(stream, filename, headers, function(err, res) {
if (err) return ctx.done(err);
if (res.statusCode !== 200) {
bucket.readStream(res, function(err, message) {
fn(err || message);
});
} else {
fn();
}
});
};
S3Bucket.prototype.upload = function(ctx, next) {
var bucket = this
, req = ctx.req;
var headers = {
'Content-Length': req.headers['content-length']
, 'Content-Type': req.headers['content-type']
};
this.client.putStream(req, ctx.url, headers, function(err, res) {
if (err) return ctx.done(err);
if (res.statusCode !== 200) {
bucket.readStream(res, function(err, message) {
ctx.done(err || message);
});
} else {
ctx.done();
}
});
req.resume();
};
S3Bucket.prototype.get = function(ctx, next) {
var bucket = this;
var url = 'https://s3.amazonaws.com/' + this.config.bucket + ctx.url;
httpUtil.redirect(ctx.res, url);
};
S3Bucket.prototype.del = function(ctx, next) {
var bucket = this;
this.client.deleteFile(ctx.url, function(err, res) {
if (err) ctx.done(err);
if (res.statusCode !== 200) {
bucket.readStream(res, function(err, message) {
ctx.done(err || message);
});
} else {
ctx.done();
}
});
};
S3Bucket.prototype.readStream = function(stream, fn) {
var buffer = '';
stream.on('data', function(data) {
buffer += data;
}).on('end', function() {
fn(null, buffer);
}).on('error', function(err) {
fn(err);
});
};
inside s3-amazon-aws folder hence I do var s3bucket = require('s3-amazon-aws');
But, now if I have to call the handle function of the module, how do I do that? Also it requires 2 parameters such as ctx,next. How do I get those parameters?
Any help would be appreciated.
The module exports the S3Bucket constructor function. Use it to create a new object. You can then call the handle() method on this object (since it's part of the object's prototype).
var S3Bucket = require('s3-amazon-aws');
var bucket = new S3Bucket(name, options);
bucket.handle(ctx, next)
Regarding the various arguments you need to read the documentation of the library.

Categories