How can I remove the extra slashes in my responses ?
I have tried JSON.parse and JSON.stringify but they are not working in my code. JSON.parse throws an error like json at position 10.
I pushed the objects of responses in one array. Then I displayed the array of objects (with array) in response.
{
"status": true,
"message": "Data Found",
"data": [
"{\"errors\":[],\"detail\":[{\"repositories\":[],\"_instance\":{\"applicationLinkId\":\"4b0d5edc-c683-3502-aed7-5f6e152b877d\",\"singleInstance\":false,\"primary\":true,\"baseUrl\":\"http://stash.computenext.com\",\"name\":\"Stash\",\"typeName\":\"Bitbucket Server\",\"id\":\"4b0d5edc-c683-3502-aed7-5f6e152b877d\",\"type\":\"stash\"}}]}"
]
}
My Code :
exports.getCommits = function (req, res) {
console.log(filename + '>>get commits>>');
var response = {
status: Boolean,
message: String,
data: String
};
var request = require('request');
var username = username;
var password = password;
var options = {
url: 'https://computenext.atlassian.net/rest/api/2/search?jql=status+%3D+Resolved+ORDER+BY+updated',
auth: {
username: username,
password: password
}
};
request(options, function (error, obj) {
if (error) {
response.message = appmsg.DATA_NT_FOUND;
response.status = false;
response.data = obj;
res.send(response);
} else {
response.message = appmsg.DATA_FOUND;
response.status = true;
response.data = JSON.parse(obj.body);
//res.send(response);
var respon = {
status: Boolean,
message: String,
data: String
};
var issueKey = response.data.issues;
var id = issueKey[0].id;
console.log(id);
var commitout = [];
for (var i = 0; i < issueKey.length; i++) {
var commits = issueKey[i].id;
console.log(commits);
var request = require('request'),
username = username,
password = password,
url =
"https://computenext.atlassian.net/rest/dev-status/1.0/issue/detail?issueId=" +
commits + "&applicationType=stash&dataType=repository",
auth = "Basic " + new Buffer(username + ":" + password).toString(
"base64");
//console.log(url);
var test = [];
request({
url: url,
headers: {
"Authorization": auth
}
}, function (err, obj1) {
if (obj1) {
var info1 = obj1.body;
commitout.push(info1);
if (issueKey.length === commitout.length) {
respon.message = appmsg.DATA_FOUND;
respon.status = true;
respon.data = commitout;
res.send(respon);
}
}
});
}
}
});
};
Try parsing the following element
commitout.push(info1);
change to,
commitout.push(JSON.parse(info1));
Update
Try the following regex
info1 = info1.replace(/\\/g, "");
commitout.push(info1);
Related
I have an api post end point which would update a customer's information in dynamodb. It is set to authenticate using AWS_IAM. I am getting 403 from my lambda when calling this api. I have allowed execute-api:Invoke permission to the api for the role lambda uses. I see in this post that I need to create a canonical request. I was able to come up with the below code and I still get a 403. I can't figure out what is missing and wish if a different eye can spot the problem. Please help!
"use strict";
const https = require("https");
const crypto = require("crypto");
exports.handler = async (event, context, callback) => {
try {
var attributes = {
customerId: 1,
body: { firstName: "abc", lastName: "xyz" }
};
await updateUsingApi(attributes.customerId, attributes.body)
.then((result) => {
var jsonResult = JSON.parse(result);
if (jsonResult.statusCode === 200) {
callback(null, {
statusCode: jsonResult.statusCode,
statusMessage: "Attributes saved successfully!"
});
} else {
callback(null, jsonResult);
}
})
.catch((err) => {
console.log("error: ", err);
callback(null, err);
});
} catch (error) {
console.error("error: ", error);
callback(null, error);
}
};
function sign(key, message) {
return crypto.createHmac("sha256", key).update(message).digest();
}
function getSignatureKey(key, dateStamp, regionName, serviceName) {
var kDate = sign("AWS4" + key, dateStamp);
var kRegion = sign(kDate, regionName);
var kService = sign(kRegion, serviceName);
var kSigning = sign(kService, "aws4_request");
return kSigning;
}
function updateUsingApi(customerId, newAttributes) {
var request = {
partitionKey: `MY_CUSTOM_PREFIX_${customerId}`,
sortKey: customerId,
payLoad: newAttributes
};
var data = JSON.stringify(request);
var apiHost = new URL(process.env.REST_API_INVOKE_URL).hostname;
var apiMethod = "POST";
var path = `/stage/postEndPoint`;
var { amzdate, authorization, contentType } = getHeaders(host, method, path);
const options = {
host: host,
path: path,
method: method,
headers: {
"X-Amz-Date": amzdate,
Authorization: authorization,
"Content-Type": contentType,
"Content-Length": data.length
}
};
return new Promise((resolve, reject) => {
const req = https.request(options, (res) => {
if (res && res.statusCode !== 200) {
console.log("response from api", res);
}
var response = {
statusCode: res.statusCode,
statusMessage: res.statusMessage
};
resolve(JSON.stringify(response));
});
req.on("error", (e) => {
console.log("error", e);
reject(e.message);
});
req.write(data);
req.end();
});
}
function getHeaders(host, method, path) {
var algorithm = "AWS4-HMAC-SHA256";
var region = "us-east-1";
var serviceName = "execute-api";
var secretKey = process.env.AWS_SECRET_ACCESS_KEY;
var accessKey = process.env.AWS_ACCESS_KEY_ID;
var contentType = "application/x-amz-json-1.0";
var now = new Date();
var amzdate = now
.toJSON()
.replace(/[-:]/g, "")
.replace(/\.[0-9]*/, "");
var datestamp = now.toJSON().replace(/-/g, "").replace(/T.*/, "");
var canonicalHeaders = `content-type:${contentType}\nhost:${host}\nx-amz-date:${amzdate}\n`;
var signedHeaders = "content-type;host;x-amz-date";
var payloadHash = crypto.createHash("sha256").update("").digest("hex");
var canonicalRequest = [
method,
path,
canonicalHeaders,
signedHeaders,
payloadHash
].join("/n");
var credentialScope = [datestamp, region, serviceName, "aws4_request"].join(
"/"
);
const sha56 = crypto
.createHash("sha256")
.update(canonicalRequest)
.digest("hex");
var stringToSign = [algorithm, amzdate, credentialScope, sha56].join("\n");
var signingKey = getSignatureKey(secretKey, datestamp, region, serviceName);
var signature = crypto
.createHmac("sha256", signingKey)
.update(stringToSign)
.digest("hex");
var authorization = `${algorithm} Credential=${accessKey}/${credentialScope}, SignedHeaders=${signedHeaders}, Signature=${signature}`;
return { amzdate, authorization, contentType };
}
I integrated the JIRA REST API in my code. In that, some response objects are displayed like "Unauthorized",
{[
{ "\n\n\n\n\n\n\n\n\n\n<html>\n\n<head>\n <title>Unauthorized (401)</title>\n },
{ "\n\n\n\n\n\n\n\n\n\n<html>\n\n<head>\n <title>Unauthorized (401)</title>\n },
{ "\n\n\n\n\n\n\n\n\n\n<html>\n\n<head>\n <title>Unauthorized (401)</title>\n },
{ \"errors\":[],\"detail\":[{\"repositories\":[],\"_instance\":{\"applicationLinkId\":\"4b0d5edc-c683-3502-aed7-5f6e152b877d\" },
{\"errors\":[],\"detail\":[{\"repositories\":[],\"_instance\":{\"applicationLinkId\":\"4b0d5edc-c683-3502-aed7-5f6e152b877d\"}
]}
My Actual Code is,
exports.getCommits = function(req, res) {
console.log(filename + '>>get commits>>');
var response = {
status : Boolean,
message : String,
data : String
};
var request = require('request');
var username = username ;
var password = password ;
var options = {
url : 'https://computenext.atlassian.net/rest/api/2/search?jql=status+%3D+Resolved+ORDER+BY+updated&maxResults=100',
auth : {
username : username,
password : password
}
};
request( options, function(error, obj) {
if (error) {
response.message = appmsg.DATA_NT_FOUND;
response.status = false;
response.data = obj;
res.send(response);
} else {
response.message = appmsg.DATA_FOUND;
response.status = true;
response.data = JSON.parse(obj.body);
var respon = {
status : Boolean,
message : String,
data : String
};
var issueKey = response.data.issues;
var id = issueKey[0].id;
var commitout = [];
var lookup_list = [];
for(var i = 0; i < issueKey.length; i++) {
var commits = issueKey[i].id;
url = "https://computenext.atlassian.net/rest/dev-status/1.0/issue/detail?issueId=" + commits + "&applicationType=stash&dataType=repository";
auth = "Basic " + new Buffer(username + ":" + password ).toString("base64");
request({url : url, headers : {"Authorization" : auth}}, function(err, obj1){
if (obj1) {
commitout.push(obj1.body);
if(issueKey.length === commitout.length){
respon.message = appmsg.DATA_FOUND;
respon.status = true;
respon.data = commitout;
res.send(respon);
}
}
});
}
}
});
};
Please give me the right solution. How can I get all JIRA's commits in response?
Some times it will display all details properly but not all time. I want a proper response for all hits.
I think "OAuth" is required for this. Now I don't have permission to view the JIRA's. So that only, it displays the "Unauthorized" error like the above.
I tried the below code. The POSTMAN and console response is:
"undefined[object Object],[object Object],[object Object],[object
Object],[object Object],[object Object],[object Object],[object
Object],"
I want the correct JSON output:
exports.getIssues = function(req, res) {
console.log(filename + '>>get Issues>>');
var response = {
status: Boolean,
message: String,
data: String
};
var request = require('request');
var username =
const.username;
var password =
const.password;
var options = {
url: 'https://computenext.atlassian.net/rest/api/2/search?jql=status+%3D+Resolved+ORDER+BY+updated',
auth: {
username: username,
password: password
}
};
request(options, function(error, obj) {
if (error) {
response.message = appmsg.DATA_NT_FOUND;
response.status = false;
response.data = obj;
res.send(response);
} else {
response.message = appmsg.DATA_FOUND;
response.status = true;
response.data = JSON.parse(obj.body);
//res.send(response);
var issueKey = response.data.issues;
// var keyData = issueKey[0].key;
// console.log(response.data.issues);
// console.log(keyData);
var output = [];
for (var i = 0; i < issueKey.length; i++) {
var issue = issueKey[i].key;
//var key = [];
//key.push(issue);
console.log(issue);
var respon = {
status: Boolean,
message: String,
data: String
};
var request = require('request'),
username =
const.username,
password =
const.username,
url = "https://computenext.atlassian.net/rest/api/2/issue/" + issue,
auth = "Basic " + new Buffer(username + ":" + password).toString("base64");
//console.log(url);
request({
url: url,
headers: {
"Authorization": auth
}
}, function(err, object) {
if (object) {
var info = object;
output.push(info); // this is not working as ouput is undefined at this point
//var pout = JSON.parse(output);
//console.log(info);
console.log("==============================================================================");
//console.log(output);
console.log("******************************************************************************");
if (issueKey.length === output.length) {
respon.message = appmsg.DATA_FOUND;
respon.status = true;
respon.data = output;
//console.log(output);
//res.send(respon);
var id = issueKey[0].id;
console.log(id);
var commitout = [];
for (var i = 0; i < issueKey.length; i++) {
var commits = issueKey[i].id;
console.log(commits);
var request = require('request'),
username =
const.username,
password =
const.password,
url = "https://computenext.atlassian.net/rest/dev-status/1.0/issue/detail?issueId=" + commits + "&applicationType=stash&dataType=repository",
auth = "Basic " + new Buffer(username + ":" + password).toString("base64");
//console.log(url);
var test = [];
request({
url: url,
headers: {
"Authorization": auth
}
}, function(err, obj1) {
if (obj1) {
var info1 = obj1;
commitout.push(info1);
var resultdone = [];
if (issueKey.length === commitout.length) {
respon.message = appmsg.DATA_FOUND;
respon.status = true;
respon.data = commitout;
// console.log(commitout);
//var test = merge(output, commitout);
//var text = output.body[0];
resultdone.push = output + commitout;
console.log(resultdone);
res.send(resultdone);
}
}
});
}
}
}
});
}
}
});
};
What are you trying to do here: resultdone.push = output + commitout;
This concatenates your arrays, hence the [object object]s. Also Why are you assigning it to resultdone.push? I think you actually want to call the method.
Try this instead:
resultdone.push(commitout.concat(output ))
1. First response is categories with two fields, category and name.
categories = [{ category: '1', name: 'category1' },
{ category: '2', name: 'category2' }]
2. Second response is commits with three fields, commit, branch and Commit ID.
commits = [{ commit: '1', branch: '1', Commit ID: 'commitid1' },
{ commit: '1', branch: '2', Commit ID: 'commitid2' }]
3. I want to create one merged JSON, based on the category that would have the following structure:
all = [
{ category: '1', name: 'category1',
body: [{ commit: '1', branch: '1', Commit ID: 'commitid1' }],
{ category: '2', name: 'category2',
body: [{ commit: '1', branch: '1', Commit ID: 'commitid2' }]
I searched and found several methods of joining or extending two json objects but nothing similar to that.
Any help would be appreciated.
My Actual Code
exports.getIssues = function(req, res) {
console.log(filename + '>>get Issues>>');
var response = {
status: Boolean,
message: String,
data: String
};
var request = require('request');
var username =
const.username;
var password =
const.password;
var options = {
url: 'https://computenext.atlassian.net/rest/api/2/search?jql=status+%3D+Resolved+ORDER+BY+updated',
auth: {
username: username,
password: password
}
};
request(options, function(error, obj) {
if (error) {
response.message = appmsg.DATA_NT_FOUND;
response.status = false;
response.data = obj;
res.send(response);
} else {
response.message = appmsg.DATA_FOUND;
response.status = true;
response.data = JSON.parse(obj.body);
//res.send(response);
var issueKey = response.data.issues;
// var keyData = issueKey[0].key;
// console.log(response.data.issues);
// console.log(keyData);
var output = [];
for (var i = 0; i < issueKey.length; i++) {
var issue = issueKey[i].key;
//var key = [];
//key.push(issue);
console.log(issue);
var respon = {
status: Boolean,
message: String,
data: String
};
var request = require('request'),
username =
const.username,
password =
const.username,
url = "https://computenext.atlassian.net/rest/api/2/issue/" + issue,
auth = "Basic " + new Buffer(username + ":" + password).toString("base64");
//console.log(url);
request({
url: url,
headers: {
"Authorization": auth
}
}, function(err, object) {
if (object) {
var info = object;
output.push(info); // this is not working as ouput is undefined at this point
//var pout = JSON.parse(output);
//console.log(info);
console.log("==============================================================================");
//console.log(output);
console.log("******************************************************************************");
if (issueKey.length === output.length) {
respon.message = appmsg.DATA_FOUND;
respon.status = true;
respon.data = output;
//console.log(output);
//res.send(respon);
var id = issueKey[0].id;
console.log(id);
var commitout = [];
for (var i = 0; i < issueKey.length; i++) {
var commits = issueKey[i].id;
console.log(commits);
var request = require('request'),
username =
const.username,
password =
const.password,
url = "https://computenext.atlassian.net/rest/dev-status/1.0/issue/detail?issueId=" + commits + "&applicationType=stash&dataType=repository",
auth = "Basic " + new Buffer(username + ":" + password).toString("base64");
//console.log(url);
var test = [];
request({
url: url,
headers: {
"Authorization": auth
}
}, function(err, obj1) {
if (obj1) {
var info1 = obj1.body;
commitout.push(info1);
if (issueKey.length === commitout.length) {
respon.message = appmsg.DATA_FOUND;
respon.status = true;
respon.data = commitout;
// console.log(commitout);
//var test = merge(output, commitout);
var resultdone = [];
request({
url: url,
headers: {
"Authorization": auth
}
}, function(err, obj1) {
if (obj1) {
var info1 = obj1.body;
commitout.push(info1);
if (issueKey.length === commitout.length) {
// console.log(commitout);
//var test = merge(output, commitout);
//var text = output.body[0];
//var resultdone = [];
resultdone.push(commitout.concat(output));
console.log(resultdone);
respon.message = appmsg.DATA_FOUND;
respon.status = true;
respon.data = resultdone;
res.send(respon);
}
}
});
}
}
}
});
}
}
});
I tested this and it worked:
var all= categories.map(function(cat,index){
cat.body=commits[index];
return cat;
})
If you want to have "body" attribute as an array:
var all= categories.map(function(cat,index){
var body = [];
body.push(commits[index]);
cat["body"] = body;
return cat;
})
console.log("all :",JSON.stringify(all));
What about this??
var all= categories.map(function(cat){
cat.body=commits.filter(x=>x.branch==cat.category);
return cat;
})
Perhaps try the following:
var all = [];
categories.forEach((e)=>{
var myIndex = categories.indexOf(e);
e.body=commits[myIndex];
all.push(e);
});
console.log(all);
You can then use JSON.stringify to get the desired output.
I have been unable to to successfully parse the returned token to authenticate final Paypal sandbox payment process. Any help or input would be greatly appreciated :)
REF:
https://github.com/petersirka/node-paypal-express-checkout
https://developer.paypal.com/docs/classic/express-checkout/in-context/integration/
Here is the error I am returned:
ACK: 'Failure',
VERSION: '52.0',
BUILD: '22708556'
L_ERRORCODE0: '10410',
L_SHORTMESSAGE0: 'Invalid token',
L_LONGMESSAGE0: 'Invalid token.',
L_SEVERITYCODE0: 'Error'
Client side:
<form id="myContainer" method="post" action="/api/payment/payone"></form>
<script>
window.paypalCheckoutReady = function () {
paypal.checkout.setup('XXX', {
environment: 'sandbox',
container: 'myContainer'
});
};
</script>
<script src="//www.paypalobjects.com/api/checkout.js" async></script>
API:
payone: function(req, res) {
var paypal = require('paypal-express-checkout').init('username', 'password', 'signature', 'return url', 'cancel url', 'debug');
paypal.pay('20130001', 10.00, 'XX', 'USD', false, function(err, url) {
if (err) {
console.log(err);
return;
}
res.redirect(url);
});
paypal.detail( "token", "PayerID", function(err, data, invoiceNumber, price) {
if (err) {
console.log(err);
return;
}
});
}
Finally, paypal-express doc:
var parser = require('url');
var https = require('https');
var qs = require('querystring');
function Paypal(username, password, signature, returnUrl, cancelUrl, debug) {
this.username = "XXX";
this.password = "XXX";
this.solutiontype = 'Mark';
this.signature = "XXX";
this.debug = debug || false;
this.returnUrl = 'XXX';
this.cancelUrl = 'XXX';
this.url = 'https://' + 'api-3t.sandbox.paypal.com' + '/nvp'; //'https://' + (debug ? 'api-3t.sandbox.paypal.com' : 'api-3t.paypal.com') + '/nvp';
this.redirect = 'https://' + 'www.sandbox.paypal.com/cgi-bin/webscr'; //https://' + (debug ? 'www.sandbox.paypal.com/cgi-bin/webscr' : 'www.paypal.com/cgi-bin/webscr');
};
Paypal.prototype.params = function() {
var self = this;
return {
USER: self.username,
PWD: self.password,
SIGNATURE: self.signature,
SOLUTIONTYPE: self.solutiontype,
VERSION: '52.0'
};
console.log(self);
};
Paypal.prototype.detail = function(token, payer, callback) {
if (token.get !== undefined && typeof(payer) === 'function') {
callback = payer;
payer = token.get.PayerID;
token = token.get.token;
}
console.log(token);
var self = this;
var params = self.params();
params.TOKEN = token;
params.METHOD = 'GetExpressCheckoutDetails';
self.request(self.url, 'POST', params, function(err, data) {
if (err) {
callback(err, data);
return;
}
if (typeof(data.CUSTOM) === 'undefined') {
callback(data, null);
return;
}
console.log('3.3');
var custom = data.CUSTOM.split('|');
var params = self.params();
params.PAYMENTACTION = 'Sale';
params.PAYERID = payer;
params.TOKEN = token;
params.AMT = custom[1];
params.CURRENCYCODE = custom[2];
params.METHOD = 'DoExpressCheckoutPayment';
self.request(self.url, 'POST', params, function(err, data) {
if (err) {
callback(err, data);
return;
}
console.log('3.4');
callback(null, data, custom[0], custom[1]);
});
});
return self;
};
Paypal.prototype.request = function(url, method, data, callback) {
var self = this;
var params = qs.stringify(data);
if (method === 'GET')
url += '?' + params;
var uri = parser.parse(url);
var headers = {};
headers['Content-Type'] = method === 'POST' ? 'application/x-www-form-urlencoded' : 'text/plain';
headers['Content-Length'] = params.length;
var location = '';
var options = { protocol: uri.protocol, auth: uri.auth, method: method || 'GET', hostname: uri.hostname, port: uri.port, path: uri.path, agent: false, headers: headers };
var response = function (res) {
var buffer = '';
res.on('data', function(chunk) {
buffer += chunk.toString('utf8');
})
req.setTimeout(exports.timeout, function() {
callback(new Error('timeout'), null);
});
res.on('end', function() {
var error = null;
var data = '';
if (res.statusCode > 200) {
error = new Error(res.statusCode);
data = buffer;
} else
data = qs.parse(buffer);
callback(error, data);
});
};
var req = https.request(options, response);
req.on('error', function(err) {
callback(err, null);
});
if (method === 'POST')
req.end(params);
else
req.end();
return self;
};
Paypal.prototype.pay = function(invoiceNumber, amount, description, currency, requireAddress, callback) {
// Backward compatibility
if (typeof(requireAddress) === 'function') {
callback = requireAddress;
requireAddress = false;
}
var self = this;
var params = self.params();
params.PAYMENTACTION = 'Sale';
params.AMT = prepareNumber(amount);
params.RETURNURL = self.returnUrl;
params.CANCELURL = self.cancelUrl;
params.DESC = description;
params.NOSHIPPING = requireAddress ? 0 : 1;
params.ALLOWNOTE = 1;
params.CURRENCYCODE = currency;
params.METHOD = 'SetExpressCheckout';
params.INVNUM = invoiceNumber;
params.CUSTOM = invoiceNumber + '|' + params.AMT + '|' + currency;
self.request(self.url, 'POST', params, function(err, data) {
if (err) {
callback(err, null);
return;
}
if (data.ACK === 'Success') {
callback(null, self.redirect + '?cmd=_express- checkout&useraction=commit&token=' + data.TOKEN);
return;
}
callback(new Error('ACK ' + data.ACK + ': ' + data.L_LONGMESSAGE0), null);
});
return self;
console.log(self);
};
function prepareNumber(num, doubleZero) {
var str = num.toString().replace(',', '.');
var index = str.indexOf('.');
if (index > -1) {
var len = str.substring(index + 1).length;
if (len === 1)
str += '0';
if (len > 2)
str = str.substring(0, index + 3);
} else {
if (doubleZero || true)
str += '.00';
}
return str;
};
exports.timeout = 10000;
exports.Paypal = Paypal;
exports.init = function(username, password, signature, returnUrl, cancelUrl, debug) {
return new Paypal(username, password, signature, returnUrl, cancelUrl, debug);
};
exports.create = function(username, password, signature, returnUrl, cancelUrl, debug) {
return exports.init(username, password, signature, returnUrl, cancelUrl, debug);
};
Usually we encounter Error 10410 if there is incorrect token or no token passed.
please make sure that you are passing the right PayPal Express token.
for information on error codes you may refer: https://developer.paypal.com/docs/classic/api/errorcodes/