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.
Related
Success localhost response
Cannot GET /u/coupons at server
Frontend script for post
<script>
var count = document.getElementById("count");
var len = document.getElementById("length");
var pattern = document.getElementById("pattern");
document.getElementById('coupons-button').onclick = function()
{
if(count.value!=="" && len.value!=="")
{
const genReq = new XMLHttpRequest();
let url = `count=${encodeURI(count.value)}&` +
`len=${encodeURI(len.value)}&` +
`pattern=${encodeURI(pattern.value)}`;
genReq.open('POST',`/u/coupons?${url}`,true);
genReq.send();
genReq.onreadystatechange = e => {
if(genReq.readyState === 4 && genReq.status === 200){
let gen = JSON.parse(genReq.response);
if (gen.state === "SUCCESS")
{
var coupons = gen.coupons;
for(var i=0;i<coupons.length;i++)
{
var div = document.createElement('div');
var text = document.createTextNode(coupons[i]);
div.appendChild(text);
document.getElementById('coupons-check').appendChild(div);
}
} else {
var div = document.createElement('div');
var text = document.createTextNode("FAIL TO GENERATE");
div.appendChild(text);
document.getElementById('coupons-check').appendChild(div);
}
}
}
}
}
Server script
admin.post( '/u/coupons' ,(req,res)=>{
let params = getParameters(req);
CouponWorker.generateCoupons({
"len":decodeURI(params.len),
"count":decodeURI(params.count),
"pattern":decodeURI(params.pattern)
}).then((_res) =>{
console.log(_res)
if(_res.success === true)
{
res.status(200).json({
"state":"SUCCESS",
"coupons":_res.coupons
});
}
else{
res.status(200).json({"state" : "FAILED"});
}
});
});
CouponWorker
const firebase = require('./Database');
const voucher_codes = require('voucher-code-generator');
exports.generateCoupons = function(params)
{
var len = params.len;
var count = params.count;
var pattern = params.pattern;
//pattern = pattern.replace(/1/g,'#');
const cpn_db = firebase.firebase.database();
var coupons;
return new Promise((resolve,reject)=>{
coupons = voucher_codes.generate({
length:len,
count:count,
prefix:"AMP-",
pattern: '####-####',
charset:"0123456789ABCDEFGHIJKLMNOPQRSTUVXYZ"
});
if(coupons!==null)
{
for(var i =0;i<count;i++)
{
cpn_db.ref('coupons/cid-'+coupons[i]).set({
"addedOn": getDateTime(),
"code" : coupons[i],
"amount" : 20,
"expireDate" : null,
"isActive" : true,
"isDeleted":false
});
}
resolve({
"success":true,
"coupons":coupons
});
}
else
{
resolve({
"success":false
});
}
});
}
Above given snaps shows the same code running on localhost and server,
localhost working fine,giving output and saving data to firbase while server response 404 not found resource.
I can not find the reason of this error.I tried url req on postman and responses are the same as 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 ))
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);
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.
Image is uploaded if validation fails after accessing the web services. I need to control it. Image should be uploaded if the validation is successful. I have defined the validation code in model created by sequelize. How to prevent it and upload image if validation is successful ?
Model code is
name : {
type : sequelize.STRING,
validate : {
notEmpty : {msg : 'The Name is required!'}
}
},
email : {
type : sequelize.STRING,
validate : {
notEmpty : {msg : 'The email field is required!'},
isEmail : {msg : 'The email format is not correct!'}
}
},
Controller code for upload image is
var storage = multer.diskStorage({
destination : function(req,file,cb){
cb(null,'public/uploads/profile/');
},
filename : function(req,file,cb){
if(!file.originalname.match(/\.(png|jpg|jpeg|gif|bmp)$/)){
var err = new Error();
err.code = 'filetype';
return cb(err);
}else{
var fileExtention = mime.extension(file.mimetype);
var uniqueFileName = uuidv1();
var uniqueImageName = uniqueFileName + '.' + fileExtention;
cb(null,uniqueImageName);
}
}
});
var upload = multer({
storage : storage,
limits : {fileSize : 10000000}
}).single('image');
EmployeeController.prototype.addEmployee = function(req,res){
upload(req,res,function(err){
if(err){
console.log(err);
if(err.code === 'LIMIT_FILE_SIZE'){
res.send({msg:'File sizee is too large. Max limit is 10mb!',status:'Failure',response:200,data:[]});
}else if(err.code === 'filetype'){
res.send({msg:'File type is invalid!',status:'Failure',response:200,data:[]});
}else{
res.send({msg:'File was not able to uploaded!',status:'Failure',response:200,data:[]});
}
}else{
if(typeof req.file === 'undefined'){
console.log('No Image Found');
var imageName = '';
}else{
console.log('Image Found!');
var imageName = '/public/uploads/profile/'+req.file.filename;
}
async.waterfall([
function(callback){
var employeeCode = 'EMP1';
var employeeCodeObj = Employee.max('id').then(max => {
var maxid = 1;
if(max){
maxid = max + 1;
}
employeeCode = "EMP"+maxid;
callback(null,employeeCode);
}).catch(err=>{
callback(err,'Failure',500,'Unable to generate employee code!',[]);
});
},
function(employeeCode,callback){
var password = randomstring.generate({
length: 8,
charset: 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!##$%&*'
});
callback(null,employeeCode,password);
},
function(employeeCode,password,callback){
var params = req.body;
var name = Helper.trimInputValue(params.name);
var email = Helper.trimInputValue(params.email);
var image = imageName;
var dob = Helper.trimInputValue(params.dob);
Employee.findOrCreate({
where : {
email : email,
},
defaults : {
name : name,
email : email,
image : image
}
}).spread(function(employeeData,created){
console.log('Success');
}).catch(sequelize.ValidationError,function(err){
var data = err.errors;
var dataErrors = Array();
if(data.length){
for(var key in data){
dataErrors.push({
'key' : data[key].path,
'msg' : data[key].message
});
}
}
callback('error','Failure',200,dataErrors,[]);
})
}
],function(error,status,response,msg,data){
return res.send({msg:msg,status:status,response:response,data:data});
});
}
});
};