Reference Error: client is not defined - node.js

I am Creating REST API Call in jira using below code :-
var loginArgs = {
data: {
"username": "singhharwinder#seasiainfotech.com",
"password": "Seasia#123"
},
headers: {
"Content-Type": "application/json"
}
};
client.post("http://jira.atlassian.com/rest/auth/1/session",
loginArgs,function (data, response) {
if (response.statusCode == 200) {
console.log('succesfully logged in, session:', data.session);
var session = data.session;
var searchArgs = {
headers: {
cookie: session.name + '=' + session.value,
"Content-Type": "application/json"
},
data: {
jql: "type=Bug AND status=Closed"
}
};
client.post("http://jira.atlassian.com/rest/api/2/search", searchArgs, function (searchResult, response) {
console.log('status code:', response.statusCode);
console.log('search result:', searchResult);
});
} else {
throw "Login failed :(";
}
});
It is giving me "Reference Error: client is not defined".
Please help me .

Related

How to send a post request on Typescript?

I have this code but I need to translate it to Typescript, and having issues finding the request module
function sendNotificationToUser(username, message, onSuccess) {
request({
url: 'https://fcm.googleapis.com/fcm/send',
method: 'POST',
headers: {
'Content-Type' :' application/json',
'Authorization': 'key='+API_KEY
},
body: JSON.stringify({
notification: {
title: message
},
to : '/topics/user_'+username
})
}, function(error, response, body) {
if (error) { console.error(error); }
else if (response.statusCode >= 400) {
console.error('HTTP Error: '+response.statusCode+' - '+response.statusMessage);
}
else {
onSuccess();
}
});
}
const response = await fetch("https://fcm.googleapis.com/fcm/send", {
method: 'POST',
body: JSON.stringify({notification: {title: message},to : '/topics/user_'+username}),
headers: {'Content-Type': 'application/json', 'Authorization': 'key='+API_KEY}
});
if (!response.ok)
{
console.error("Error");
}
else if (response.statusCode >= 400) {
console.error('HTTP Error: '+response.statusCode+' - '+response.statusMessage);
}
else{
onSuccess();
}

How to send webhook to jotForm from my site?

I'm working to send the data from my server to the webhook.
I'm using a "REQUEST" service, but I'm getting an error. My request hits there but I'm getting an error.
var request = require('request');
var data:any = [];
data[5] = {email5 : "abc#gmail.com"};
request.post({
"url": "https://api.jotform.com/form/formId/submissions?apiKey=apikey",
"json": {
submission : data
},
"headers": {
"Content-type": "application/json"
}
}, (error:any, response:any) => {
if (error) {
console.log(error);
}
else {
if(response){
console.log(response);
console.log('=================');
}
}
});
I'm getting an error of questionId.
Here is my error
body:
{ responseCode: 500,
message: 'error',
content: 'QuestionID not found on form questions!',
duration: '29ms' } }
Please help me!

Using Bitbucket REST Api v2 - Unable to specify project when creating new repository

The repository is created but it is not added to the project specified in the request. I read somewhere it could be because I am using form keyword in the request but I am not sure how to get it working.
let event = {
reponame: "DWM_Test-3",
visibility: "private",
description: "This repo is created by DWM",
language: "php",
project: {"key": "DWMT"},
wiki: true,
issues: true,
username: "xyz"
};
This is my function
const createRepo = (access_token, event) => {
request({
url: 'https://api.bitbucket.org/2.0/repositories/' + event.username + '/' + _.kebabCase(event.reponame),
method: 'POST',
headers: {'Authorization': 'Bearer ' + access_token, 'Content-Type': 'application/json'},
form: {
"scm": "git",
"name": event.reponame,
"is_private": event.visibility === 'private' ? true : false,
"description": event.description,
"language": event.language,
"project": event.project,
"has_issues": event.issues,
"has_wiki": event.wiki,
"fork_policy": "no_public_forks"
}
}, function (err, res) {
if (err) {
console.log(err);
}
let json = JSON.parse(res.body);
if (res.statusCode === 401) {
console.log(json);
return json;
// reject(new Error(json.error.message));
}
if (res.statusCode === 400) {
console.log(json);
return json;
// reject(new Error(json.error.message));
}
if (res.statusCode === 200) {
console.log(chalk.green('You can view it here: ' + json.links.html.href + '\n'));
}
});
};
Managed to figure it out.
let data = {
"scm": "git",
"name": event.repoName,
"is_private": event.visibility === 'private',
"description": event.description,
"language": event.language,
"project": event.project,
"has_issues": false,
"has_wiki": true,
"fork_policy": "no_public_forks"
};
const createRepo = (access_token) => {
request({
url: 'https://api.bitbucket.org/2.0/repositories/' + event.owner + '/' + _.kebabCase(event.repoName),
method: 'POST',
headers: {'Authorization': 'Bearer ' + access_token, 'Content-Type': 'application/json'},
// form : {
// "scm": "git",
// "name": event.reponame,
// "is_private": event.visibility === 'private' ? true : false,
// "description": event.description,
// "language": event.language,
// "project": event.project,
// "has_issues": event.issues,
// "has_wiki": event.wiki,
// "fork_policy": "no_public_forks"
//
// }
body: JSON.stringify(data)
}, function (err, res) {
if (err) {
callback(err);
}
let json = JSON.parse(res.body);
if (res.statusCode === 401) {
response.statusCode = 401;
response.message = json;
// console.log(json);
callback(null, response)
// reject(new Error(json.error.message));
}
if (res.statusCode === 400) {
response.statusCode = 400;
response.message = json;
// console.log(json);
callback(null, response)
// reject(new Error(json.error.message));
}
if (res.statusCode === 200) {
response.statusCode = 200;
response.url = json.links.html.href;
console.log(chalk.green('\n' + json.name + ' created sucessfully.'));
console.log(chalk.green('You can view it here: ' + json.links.html.href + '\n'));
callback(null, response)
}
});
};

nodejs try catch and res.status usage

i am still not so happy about my code in regards to structuring of try/catch and res.status.
I guess the catch block will never reached when an error within the request is coming back as response right ?
What is the best way to structure this, i am only interested in giving back the correct res.status in regards to the occuring error ??
setPublicLink: async (req, res, next) => {
try{
console.log('Entering setPublicLink');
var mytoken = "Bearer "+process.env.MY_TOKEN;
request({
url: ' https://content.dropboxapi.com/2/files/upload',
headers: {
'content-type' : 'application/octet-stream',
'authorization' : mytoken
},
encoding: null,
method: 'POST',
body: fs.createReadStream(fileItem.path),
encoding: null
}, (error, response, body) => {
if (error) {
console.log(error);
console.log(response);
//return res.status(401).json({error: 'Upload of file was not successful.'});
} else if ( response.statusCode == 200) {
//nothing to do
} else {
console.log(response);
return res.status(401).json({error: 'Upload of file was not successful.'});
}
});
request({
url: 'https://api.dropboxapi.com/2/sharing/create_shared_link_with_settings',
headers: {
'content-type' : 'application/json',
'authorization' : mytoken
},
method: 'POST',
body: JSON.stringify(reqBodyJson)
}, (error, response, body) => {
if (error) {
console.log(error);
console.log(response);
return res.status(401).json({error: 'Error when trying to set public link'});
} else if ( response.statusCode == 200) {
return res.status(200).json({success: 'Public Link has been set successfully.'});
} else if ( response.statusCode == 409) {
return res.status(409).json({error: 'Nothing to set. Public link already exists.'});
} else {
return res.status(401).json({error: 'Could not set public link'});
}
});
}
catch (err) {
console.log('Error Occured : '+ err);
return res.status(401).json({error: 'Error occured trying to set publicLink'});
}
},
your code will never hit the catch block since your handling all off the errors. but your code style is difficult to maintain it is better to use promises for example you could use request-promise module then your code will be somthing like if you have node 8+:
setPublicLink: async (req, res, next) => {
try{
console.log('Entering setPublicLink');
var mytoken = "Bearer "+process.env.MY_TOKEN;
var response = await requestPromise({
url: ' https://content.dropboxapi.com/2/files/upload',
headers: {
'content-type' : 'application/octet-stream',
'authorization' : mytoken
},
encoding: null,
method: 'POST',
body: fs.createReadStream(fileItem.path),
encoding: null
});
var response1 = await requestPromise({
url:
'https://api.dropboxapi.com/2/sharing/create_shared_link_with_settings',
headers: {
'content-type' : 'application/json',
'authorization' : mytoken
},
method: 'POST',
body: JSON.stringify(reqBodyJson)
});
res.send({success: 'Public Link has been set successfully.'});// it sends 200 automatically
}
catch(ex){
res.sendStatus(401);
}
}
also you can get the response headers.

Testing Auth0 API Patch Request

Trying to test Auth0 API patch request to modify user_metadata.
Using mocha and superagent for testing.
Get succeeds, but doing a patch with a userid and sending
.send({ "metadata": { "nickname": "Jill" } })
in the mocha testing file does not work.
router.patch('/:id', function(req, res, next) {
var options = {
method: 'PATCH',
url: 'https://mrides.auth0.com/api/v2/users/' + req.params.id,
headers: {
Authorization: "Bearer " + apiToken
},
data: req.body
}
request.patch(options, function(err, response, body) {
if(!err && response.statusCode == 200) {
res.send(JSON.parse(body))
} else {
res.status(500).send(err);
}
})
});
Error:
{
"statusCode": 400,
"error": "Bad Request",
"message": "Payload validation error: 'Expected type object but found type null'.",
"errorCode": "invalid_body"
}
Had seen this question:
Auth0 API Request
but it did not work when trying:
data: JSON.stringify(req.body)
Any help or links on how to propery modify user_metadata?
Have also been looking through Auth0 docs but no advancement yet.
change options following way:
var options = {
method: 'PATCH',
url: 'https://mrides.auth0.com/api/v2/users/' + req.params.id,
headers: {
Authorization: "Bearer " + apiToken
},
// change here
body: req.body
}
request.patch(options, function(err, response, body) {
if(!err && response.statusCode == 200) {
res.send(JSON.parse(body))
} else {
res.status(500).send(err);
}
})
};

Resources