UnhandledPromiseRejectionWarning in Node App - node.js

I'm building a crypto tracker in node. I have a list of addresses in the Wallet collection. I'm wanting to perform an API call to ethplorer for each address. I'm getting the error UnhandledPromiseRejectionWarning and also req.next is not a function. I'm confused because I'm not even using a req.next anywhere.
Any idea what's causing this error?
app.get('/ethplorer', function(req, res) {
const rp = require('request-promise');
Wallet.find({}).then(function(wallets) {
var allData = [];
wallets.forEach(function(w) {
const requestOptions = {
method: 'GET',
url: `https://api.ethplorer.io/getAddressInfo/${w.address}`,
qs: {
'apiKey': 'aaa'
},
json: true
};
rp(requestOptions).then(response => {
allData.push(response);
}).catch(function(err) {
console.log(err);
});
res.render('ethereum', {user: req.user, eth: allData});
});
});
});

allData is not going to be populated, nor should you do res.render in a loop
Rewritten to use async/await, avoid then() callbacks its messy
const rp = require('request-promise')
app.get('/ethplorer', async function (req, res, next) {
try {
const requestOptions = {
method: 'GET',
qs: {
'apiKey': 'aaa'
},
json: true
}
let allData = []
for (let wallet of await Wallet.find({})) {
try {
allData.push(await rp({
...requestOptions,
url: 'https://api.ethplorer.io/getAddressInfo/' + wallet.address
}))
} catch (_) {}
}
res.render('ethereum', {
user: req.user,
eth: allData
})
} catch (e) {
next(e)
}
})

Related

Keep getting pending request when trying to call endpoint, what's wrong?

I have made an endpoint to get token for paytm payment integration. In backend when i'm calling api i'm getting reqdata json but in frontend when i'm logging await transactionAPI, i'm getting only pending promise. i've tried using then in backend in PaytmChecksum.generateSignature method & in frontend in fetch but nothing is working. Keep getting the same result. Pls help.
Frontend code:
const makePayment = async () => {
const data = {
oid: String(new Date().valueOf()),
amount: '1.00',
email: 'abc#gmail.com',
};
let transactionAPI = fetch('http://localhost:3000/api/pretransact', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
});
console.log(await transactionAPI);
}
Backend code:
const https = require('https');
const PaytmChecksum = require('./PaytmChecksum');
export default async function handler(req, res) {
if (req.method == 'POST') {
const { oid, amount, email } = req.body;
let mid = process.env.PAYTM_MID;
let paytmParams = {};
paytmParams.body = {
requestType: 'Payment',
mid,
websiteName: process.env.WEBSITE,
orderId: oid,
callbackUrl: 'http://localhost:3000/api/callback',
txnAmount: {
value: amount,
currency: 'INR',
},
userInfo: {
custId: email,
},
};
const checksum = await PaytmChecksum.generateSignature(
JSON.stringify(paytmParams.body),
process.env.MERCHANT_KEY
);
paytmParams.head = {
signature: checksum,
};
var post_data = JSON.stringify(paytmParams);
const requestAsync = () => {
return new Promise((resolve, reject) => {
var options = {
hostname: 'securegw-stage.paytm.in',
// hostname: 'securegw.paytm.in',
port: 443,
path: `/theia/api/v1/initiateTransaction?mid=${mid}&orderId=${oid}`,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': post_data.length,
},
};
var response = '';
var post_req = https.request(options, function (post_res) {
post_res.on('data', function (chunk) {
response += chunk;
});
post_res.on('end', function () {
resolve(response);
});
});
post_req.write(post_data);
post_req.end();
});
};
const reqdata = await requestAsync();
res.send(200).json(reqdata);
}
}

Using Sequelize Operators with values from JSON body

New to Sequelize and SQL queries in general but wondering there is a simple way to use values sent in JSON body from the client when querying the database. I tried a number of variations of the below without success.
A simple example of the server route looks like this:
builder.post('/', async (req, res) => {
let track_criteria1 = req.body.criteria1;
let track_criteria2 = req.body.criteria2;
const customPlaylist = await req.context.models.Song.findAll({
where: {
[Op.and]: [
{ criteria1: { [Op.gt]: track_criteria1 } },
{ criteria2: { [Op.gt]: track_criteria2 } }
]}
});
return res.send(customPlaylist);
});
module.exports = builder;
For context, the request from the client looks like this:
const handleSubmit = async event => {
event.preventDefault()
updateStatus(PENDING)
const response = await fetch(`http://localhost:8000/playlistbuilder/`, {
method: 'POST',
contentType: 'application/json',
body: JSON.stringify({
criteria1: state.trackCriteria.criteriaOne,
criteria2: state.trackCriteria.criteriaTwo,
})
})
const tracks = await response.json()
setcustomTracks(tracks)
setTimeout(() => {
updateStatus(SUCCESS)
}, 2000)
}
Maybe this is wishful thinking! Right now there is no error but the SQL query logs out like: WHERE ("songs"."criteria1" > NULL AND "songs"."criteria2" > NULL);
Thanks!
If anyone else ends up here. I solved it by moving the contentType into a header. The updated submit handler looks like:
const handleSubmit = async event => {
event.preventDefault()
updateStatus(PENDING)
const response = await fetch(`http://localhost:8000/playlistbuilder/`, {
headers: {
'Content-Type':'application/json'
},
method: 'POST',
body: JSON.stringify({
criteria1: state.trackCriteria.criteriaOne,
criteria2: state.trackCriteria.criteriaTwo,
}),
})
I don't know enough about this yet to explain WHY this works. I'll research that tomorrow, but it is now working.

How to send parameters through axios get method in react?

I have a axios GET method and I need to pass parameters with the get request. I am calling the GET method in Client side (React.js) like this,
const [Cart] = useState([]);
const user = {
userId : session.userId
};
console.log(user);
useEffect((user) => {
if(session.userId !== null){
//Axios.get('http://localhost:5000/api/cart/getCart', user) <- I tried both these ways
Axios({
method: 'GET',
url: 'http://localhost:5000/api/cart/getCart',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
data: {},
params: {
"userId" : session.userId
}
})
.then(res => {
const cart = res.data;
let tempProducts = [];
cart.data.forEach(item => {
const singleItem = {...item};
tempProducts = [...tempProducts, singleItem];
});
this.setState(() => {
return {Cart: tempProducts};
});
})
}
console.log(Cart)
});
But in server side (node.js), it doesn't get the parameter value.
router.get('/getCart', (req, res) => {
console.log(req.body.userId) //This gives the output as undefined
User.findOne({_id: req.body.userId}
,(err, userInfo) => {
res.json(userInfo.Cart);
})
});
I implemented the uncommented axios.get request by referring to this. Can you please help me to find the error? Or can you suggest me any other method to do this? Thanks
UseEffect :
axios.get('/api', {
params: {
foo: 'bar'
}
});
Server :
function get(req, res, next) {
let param = req.query.foo
.....
}

Not return value from custom helper

I have problem with my node.js helper. My helper send post request to payu API, API return access_token which i need. If receive access_token then i need return him.
My code:
module.exports = {
createPaymentToken: async () => {
const response = await request({
method: 'POST',
json: false,
url: payuAuthUrl,
form: {
'grant_type': 'client_credentials',
'client_id': payuMerchantID,
'client_secret': payuSecret,
}
},
function (error, response, body) {
if (response) {
const result = (JSON.parse(body));
const token = result.access_token;
return token;
}
}
);
},
When i add console.log(token) before return token, then i see my access_token. The problem is when I want to pass this token to the controller, i.e. it reaches me undefined.
My controller
testPayment: async (req, res) => {
var result = await payuHelper.createPaymentToken();
res.send({
result
});
},
I have no idea what I'm doing wrong.
Your return statement was placed inside callback, so the createPaymentToken function doesn't return anything, just fix your code like sample below:
module.exports = {
createPaymentToken: () => {
return new Promise((resolve, reject) => {
request({
method: 'POST',
json: false,
url: payuAuthUrl,
form: {
'grant_type': 'client_credentials',
'client_id': payuMerchantID,
'client_secret': payuSecret,
}
},
function (error, response, body) {
if (error) {
return reject(error)
}
if (response) {
const result = (JSON.parse(body));
const token = result.access_token;
return resolve(token);
}
}
);
})
},
}
Promise document

Node.JS - Return Promise Gives 'undefined' [duplicate]

This question already has answers here:
How do I wait for a promise to finish before returning the variable of a function?
(4 answers)
Closed 4 years ago.
When I try to call this oauth-1.0 API request,
const request = require('request');
const OAuth = require('oauth-1.0a');
const crypto = require('crypto');
function main(params) {
// Dependencies
// Initialize
const oauth = OAuth({
consumer: {
key: '****',
secret: '****'
},
signature_method: 'HMAC-SHA1',
hash_function(base_string, key) {
return crypto.createHmac('sha1', key).update(base_string).digest('base64');
}
});
// Note: The token is optional for some requests
const token = {
key: '****',
secret: '****'
};
const request_data = {
url: 'http://****/rest/V1/products/12345',
method: 'GET',
//data: { status: 'Hello Ladies + Gentlemen, a signed OAuth request!' }
};
return new Promise((resolve, reject) => {
request({
url: request_data.url,
method: request_data.method,
form: request_data.data,
headers: oauth.toHeader(oauth.authorize(request_data, token))
}, function (err, res, body) {
//console.log(res.body.name);
if (err){
reject({
statusCode: 500,
headers: { 'Content-Type': 'application/json' },
body: {'message': 'Error processing your request' },
});
} else {
resolve({
body: JSON.parse(body),
})
}
});
});
};
exports.main = main;
it returns
Promise { < pending > }
undefined
However when I just use console.log(body), it gives the correct result
..................
.................
....
.....
.....
.....
Actually it it works correct and returns Promise.
So if you want to get "data" from promise, you should use Promise.then()
Like in this example from MDN.
const promise1 = new Promise(function(resolve, reject) {
resolve('Success!');
});
promise1.then(function(value) {
console.log(value);
// expected output: "Success!"
});
Hope it helps!

Resources