Using Request to post from NodeJS - node.js

I am running into an issue with posting a json doc via request from my nodeJs app.
The problem is for me how to pass the json doc to post. Here is what works for me
const options = {
url: 'http://localhost/message/send/981f1507-2df2-4011-8f55-5460897fcde6',
method: 'POST',
json: true,
body: { "message": {
"subject": "Meet for lunch?",
"body": {
"contentType": "html",
"content": "</p>\r\n\r\n<ul type=\"disc\">\r\n\t<li><strong>Ready to Use Experiences</strong> – Get instant access to our fully configured and integrated environments allowing you to use and experience the products as a customer would in their own deployment. We’ve set up the products alongside partner solutions so you can experience the entire ecosystem including Office 365, Salesforce, and more. </li>\r\n</ul>"
},
"toRecipients": [
{
"emailAddress": {
"address": "test#ueser.com"
}} ]}}}
request(options, function(err, res, body) {
console.log(res.statusCode)
})
the problem i have is if i want to pass the body from a string like this
var mybody = `{ "message": {
"subject": "Meet for lunch?",
"body": {
"contentType": "html",
"content": "This is a test"
},
"toRecipients": [
{
"emailAddress": {
"address": "test#user.com"
}
}]}}`
and then call it like this
const options = {
url: 'http://localhost/message/send/981f1507-2df2-4011-8f55-5460897fcde6',
method: 'POST',
json: true,
body: mybody
}
request(options, function(err, res, body) {
console.log(res.statusCode)
})
which throws errors like
SyntaxError: Unexpected token " in JSON at position 0

Have you tried using stringify? Node.js has a a built in module called querystring.
const querystring = require("querystring");
const myStringBody = querystring.stringify(myBody);
Then write it to your request.
req.write(myStringBody);

Related

How to add parameters to Axios

I am trying to implement axios POST to itop, everything works fine using POSTMAN for me to hard code "title, description, name and first name". Basically at the first start I want to make it like a webpage to input data and then submit the data to itop using POST.
Instead of me manually adding the required parameters, I want to grab the parameters from a form. As for the current script that I have, it said the URL is wrong because the actual URL should be like this instead of below (actual URL from postman: http://test.com/itop/webservices/rest.php?version=1.3&json_data={\n "operation": "core/create",\n "comment": "Synchronization from blah...",\n "class": "UserRequest",\n "output_fields": "id, friendlyname",\n "fields":\n {\n "org_id": "SELECT Organization WHERE name = \"TEST\"",\n "caller_id":\n {\n "name": "name",\n "first_name": "first_name"\n },\n "title": "Test",\n "description": "Test Ticket"\n }\n}')
Here is the code, this code will give out 404 because the request is not correct
app.post('/form-submit', (req, res) => {
let bodyData = {
"operation": "core/create",
"class": "UserRequest",
"output_fields": "id, friendlyname",
"fields": {
"org_id": "SELECT Organization WHERE name = 'TEST'",
},
"caller_id": {
"name": req.body.name,
"first_name": req.body.first_name
},
"title": req.body.title,
"description": req.body.description,
}
let axiosConfig = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic c2FtdWVsLmNoYW5AbHlasdfasdZS5jb206W04wemgxa2FyMV0=',
'Cookie': 'itop-ffb5bc6b0d3aasdfa53a36b=g20efh3399am02aq7v8tif1b7l'
},
}
axios.post('http://test.com/itop/webservice/rest.php?version=1.3&json_data=', bodyData, axiosConfig)
.then(function (response) {
console.log("Ticket created:" + response.data)
})
.catch(function (error) {
console.log(error)
})
})
Thanks ahead for any insight provided

Can't get a succesful jira create issue api response

I am trying to call jira rest api POST /rest/api/3/issue from a node js application. I am getting the following error even though am passing correct details. I am passing issueType as 10103 and remaining sensitive params as required. Here is my
nodejs code.
app.post("/webhook", function(req,res,next){
console.log(req.body);
let options = {
method: 'POST',
url: req.body.tags["jira:endpointURL"]+"/rest/api/3/issue",
auth: {
user: req.body.tags["jira:user"],
password: req.body.tags["jira:token"]
},
headers: {
'Content-Type': 'application/json'
},
json: {
"update": {},
"fields": {
//"summary": req.body["subject"],
"summary": "Test",
"description": {
"type": "doc",
"version": 1,
"content": [
{
"type": "paragraph",
"content": [
{
"text": "body",
"type": "text"
}
]
}
]
},
"issuetype": {
"id": req.body.tags["jira:issueType"]
},
"project": {
"key": req.body.tags["jira:project"]
}
}
}
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(
'Response: ' + response.statusCode + ' ' + response.statusMessage
);
console.log(body);
res.send("OK");
});
});
Error thrown
summary: "Field 'summary' cannot be set. It is not on the appropriate screen, or unknown.",
description: "Field 'description' cannot be set. It is not on the appropriate screen
You have to configure the fields to the screens first.
See:
https://support.atlassian.com/jira-cloud-administration/docs/add-a-custom-field-to-a-screen/
https://support.atlassian.com/jira-cloud-administration/docs/configure-issue-screens/#Configure-a-screen--x27-s-tabs-and-fields

Post request works as node script, but not on localhost

I have this post request to JIRA to create an issue:
require('isomorphic-fetch');
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
var summ = "Review Test Ticket";
var issue = {
"fields": {
"project":
{
"key": "ABC"
},
"summary": summ,
"description": "This is a test JIRA issue creation",
"issuetype": {
"name": "Story"
},
"assignee": {
"name": "myname"
},
"customfield_10902": [{ "value": "Red Team" }],
"customfield_10008": 1
}
};
var missue = JSON.stringify(issue)
fetch("https://my_jira_host/jira/rest/api/2/issue/", {
body: missue,
headers: {
"Authorization": "Basic my_auth_token",
"Content-Type": "application/json"
},
method: "POST"
})
.then(function( data ) {
console.log(data);
}).catch(function(data) {
alert(data);
});
If the above code is in a file called "my_file.js" if I run node my_file.js the ticket is successfully created.
However, if I move that code inside a function that runs on button click in my react app, and then run the app (on localhost or a server) then it fails. I get a 403. The alert displayed from my catch is: TypeError: NetworkError when attempting to fetch resource.
I have tried absolutely everything. Have no idea where to go from here. Any ideas?

Atlassian Connect-Express: JIRA REST API authentication within the JIRA plugin

i am using the atlassian-connect-express toolkit for creating Atlassian Connect based Add-ons with Node.js.
It provides Automatic JWT authentication of inbound requests as well as JWT signing for outbound requests back to the host.
The add-on is authenticated when i install it in the JIRA dashboard and return the following pay-load:
{ key: 'my-add-on',
clientKey: '*****',
publicKey: '********'
sharedSecret: '*****'
serverVersion: '100082',
pluginsVersion: '1.3.491',
baseUrl: 'https://myaccount.atlassian.net',
productType: 'jira',
description: 'Atlassian JIRA at https://myaccount.atlassian.net ',
eventType: 'installed' }
But i am not able to authenticate the JIRA Rest Api with the JWT token generated by the framework. It throws below error message.
404 '{"errorMessages":["Issue does not exist or you do not have permission to see it."],"errors":{}}'
below is the code when i send a GET request:
app.get('/getissue', addon.authenticate(), function(req, res){
var request = require('request');
request({
url: 'https://myaccount.atlassian.net/rest/api/2/issue/ABC-1',
method: 'GET',
}, function(error, response, body){
if(error){
console.log("error!");
}else{
console.log(response.statusCode, body);
}
});
res.render('getissue');
});
Below is the code for my app descriptor file:
{
"key": "my-add-on",
"name": "Ping Pong",
"description": "My very first add-on",
"vendor": {
"name": "Ping Pong",
"url": "https://www.example.com"
},
"baseUrl": "{{localBaseUrl}}",
"links": {
"self": "{{localBaseUrl}}/atlassian-connect.json",
"homepage": "{{localBaseUrl}}/atlassian-connect.json"
},
"authentication": {
"type": "jwt"
},
"lifecycle": {
"installed": "/installed"
},
"scopes": [
"READ",
"WRITE"
],
"modules": {
"generalPages": [
{
"key": "hello-world-page-jira",
"location": "system.top.navigation.bar",
"name": {
"value": "Hello World"
},
"url": "/hello-world",
"conditions": [{
"condition": "user_is_logged_in"
}]
},
{
"key": "getissue-jira",
"location": "system.top.navigation.bar",
"name": {
"value": "Get Issue"
},
"url": "/getissue",
"conditions": [{
"condition": "user_is_logged_in"
}]
}
]
}
}
I am pretty sure this is not the correct way i am doing, Either i should use OAuth. But i want to make the JWT method for authentication work here.
Got it working by checking in here Atlassian Connect for Node.js Express Docs
Within JIRA ADD-On Signed HTTP Requests works like below. GET and POST both.
GET:
app.get('/getissue', addon.authenticate(), function(req, res){
var httpClient = addon.httpClient(req);
httpClient.get('rest/api/2/issue/ABC-1',
function(err, resp, body) {
Response = JSON.parse(body);
if(err){
console.log(err);
}else {
console.log('Sucessful')
}
});
res.send(response);
});
POST:
var httpClient = addon.httpClient(req);
var postdata = {
"fields": {
"project":
{
"key": "MYW"
},
"summary": "My Story Name",
"description":"My Story Description",
"issuetype": {
"name": "Story"
}
}
}
httpClient.post({
url: '/rest/api/2/issue/' ,
headers: {
'X-Atlassian-Token': 'nocheck'
},
json: postdata
},function (err, httpResponse, body) {
if (err) {
return console.error('Error', err);
}
console.log('Response',+httpResponse)
});
You should be using global variable 'AP' that's initialized by JIRA along with your add-on execution. You may explore it with Chrome/Firefox Debug.
Have you tried calling ?
AP.request(..,...);
instead of "var request = require('request');"
You may set at the top of the script follwing to pass JS hinters and IDE validations:
/* global AP */
And when using AP the URL should look like:
url: /rest/api/2/issue/ABC-1
instead of:
url: https://myaccount.atlassian.net/rest/api/2/issue/ABC-1
My assumption is that ABC-1 issue and user credentials are verified and the user is able to access ABC-1 through JIRA UI.
Here is doc for ref.: https://developer.atlassian.com/cloud/jira/software/jsapi/request/

Create an Issue with Jira API REST

When I try to create an Issue via the Jira API REST, I get a 500 Internal server error, I succeeded to get an issue from a project with a get-request but when I try the post-request to create a new issue it doesn't work I get the error.
Here is my JavaScript code :
createIssue: function(req, res) {
var Http = require('machinepack-http');
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
Http.sendHttpRequest({
url: '/rest/api/2/issue/',
baseUrl: 'https://jira.mydomain.com',
method: 'post',
data: {
"fields": {
"project": {
"key": "TEST"
},
"summary": "REST ye merry gentlemen.",
"description": "Creating of an issue using project keys and issue type names using the REST API",
"issuetype": {
"name": "Bug"
}
}
},
headers: {
"Authorization": "Basic YWxbG9wMS4zp0bWFuzeThYS5l1TIqaXoxOTg5554Jh"
},
}).exec({
serverError: function(result) {
res.send("server error" + JSON.stringify(result))
},
success: function(result) {
res.send("issue has been created succefly");
},
});
}
Error content :
{
"body": "{\"errorMessages\":[\"Internal server error\"],\"errors\":{}}",
"headers": "{\"server\":\"nginx/1.6.0\",\"date\":\"Tue, 14 Apr 2015 13:45:38 GMT\",\"content-type\":\"application/json;charset=UTF-8\",\"transfer-encoding\":\"chunked\",\"connection\":\"close\",\"x-arequestid\":\"945x246734x1\",\"set-cookie\":[\"JSESSIONID=838923A79DA31F77BDD62510399065CF; Path=/; HttpOnly\",\"atlassian.xsrf.token=BQIV-TVLW-FGBG-OTYU|63c1b4a7b87a9367fff6185f0101c415f757e85b|lin; Path=/\"],\"x-seraph-loginreason\":\"OK\",\"x-asessionid\":\"ughpoh\",\"x-ausername\":\"alaa\",\"cache-control\":\"no-cache, no-store, no-transform\",\"x-content-type-options\":\"nosniff\"}",
"status": 500
}
Use params instead of data
JS:-
createIssue: function(req, res) {
var Http = require('machinepack-http');
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
Http.sendHttpRequest({
url: '/rest/api/2/issue/',
baseUrl: 'https://jira.mydomain.com',
method: 'post',
params: {
"fields": {
"project": {
"key": "TASC"
},
"summary": "REST ye merry gentlemen.",
"description": "Creating of an issue using project keys and issue type names using the REST API",
"issuetype": {
"name": "Bug"
}
}
},
headers: {
"Authorization": "Basic YWxbG9wMS4zp0bWFuzeThYS5l1TIqaXoxOTg5554Jh"
},
}).exec({
serverError: function(result) {
res.send("server error" + JSON.stringify(result))
},
success: function(result) {
res.send("issue has been created succefly");
},
});
}
Reference
It looks like it's expecting some non-null value when it's trying to parse the project or issuetype fields, though without the full stacktrace, it's hard to be sure.
You might try adding an id property to both the project and issuetype fields:
params: {
"fields": {
"project": {
"key": "TASC",
"id": "10001"
},
"summary": "REST ye merry gentlemen.",
"description": "Creating of an issue using project keys and issue type names using the REST API",
"issuetype": {
"id": "1",
"name": "Bug"
}
}
}
Obviously you'll want to make sure to use an appropriate value in both cases.

Resources