Tampermonkey GM_xmlhttpRequest not sending Request properly - jira

I am trying to implement a tampermonkey script that triggers an API call to a Jira instance to create a ticket with some information found in the page I am on (on a different domain).
Here's what I've tried:
async function createJiraTicket() {
let elements = await obtainThingsForCreatingJiraTicket();
let createJiraTicketUrl = `https://${jiraDomain}/rest/api/latest/issue`;
let requestDataForCreation =`
{
"fields": {
"project": { "key": "${elements.project}" },
"summary": "${elements.title}",
"description": "nothing",
"issuetype": {"name": "Issue" }
}
}`;
GM_xmlhttpRequest ( {
method: "POST",
url: `${http}://${createJiraTicketUrl}`,
user: 'user:pwd', // also tried user:'user', password:'pwd',
data: requestDataForCreation,
header: 'Accept: application/json',
dataType: 'json',
contentType: 'application/json',
onload: function (response) {
jiraTicketLog(`[Ajax] Response from Ajax call Received: `);
}
} );
However, when I run createJiraTicket(), I am getting the following error:
Uncaught TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them
at <anonymous>:1:7
I have established the correct #connect tags on the script, so I am pretty blind on where the problem may be...
Can someone help?
Thanks

So I came up with the answer to fix it, apparently it was a number of different details:
So,
Authorization had to be included onto the headers, coded on base64 and keyworded "Basic".
User-Agent needs to be overriden on headers, with any dummy string.
overrideMimeType needed to be set to json.
That all made the trick.
This was the working code.
let createJiraTicketUrl = `//${jiraDomain}/rest/api/latest/issue`;
let authentication = btoa('admin:foobar1');
GM.xmlHttpRequest({
method: "POST",
headers: {
'Accept': 'application/json',
"Content-Type": "application/json",
"Authorization": `Basic ${authentication}`,
"User-Agent": "lolol"
},
url: `${http}:${createJiraTicketUrl}`,
data: JSON.stringify(requestDataForCreation),
dataType: 'json',
contentType: 'application/json',
overrideMimeType: 'application/json',
onload: function (response) {
let url = `${http}://${jiraDomain}/browse/${JSON.parse(response.response).key}`;
log(`${JSON.parse(response.response).key} ticket created: ${url}`);
openJiraTicket(url);
}

Related

Why doesn't my Zapier Integration Dynamic Field work?

I have a simple zapier integration built and it works perfectly. However, I'm adding dynamic fields. Again it all seems to work perfectly when I test the zap. My dynamic form fields appear just as I expected.
The problem is sending the value of those dynamic forms to my API. I am using the zapier console and when I configure the API request I am using the following:
Where body['custom_fields'] is supposed to send all my dynamic fields or even all of the fields. But when it hits my API custom_fields parameter is blank.
const options = {
url: 'https://example_url/endpoint',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': `Bearer ${bundle.authData.auth_token}`
},
body: {
'email': bundle.inputData.email,
'custom_fields': bundle.inputData
/**
I've tried the following with no luck:
'custom_fields': bundle.inputData.fields
'custom_fields': bundle.inputData.undefined
'custom_fields': bundle.inputData
*/
}
}
return z.request(options)
.then((response) => {
response.throwForStatus();
const results = response.json;
// You can do any parsing you need for results here before returning them
return results;
});
Ok after a few days, it's the simplest answer.
Obviously an object can't be sent over params.
so instead of having
'custom_fields': bundle.inputData
I just add the whole object to the params and it takes care of all keys and values
params: bundle.inputData
Here is the full body
const options = {
url: 'https://apiendpoint.com',
method: 'POST',
headers: {
'Authorization': `Bearer ${bundle.authData.auth_token}`
},
params: bundle.inputData,
}
return z.request(options)
.then((response) => {
response.throwForStatus();
const results = response.json;
// You can do any parsing you need for results here before returning them
return results;
});
You can use the spread operator ...bundle.inputData like explained in the doc:
https://platform.zapier.com/docs/input-designer#how-to-include-dynamic-fields-in-api-calls
const options = {
url: 'https://example_url/endpoint',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': `Bearer ${bundle.authData.auth_token}`
},
body: { ...bundle.inputData }
}
You can even namespace your request data like that:
body: {
request: { ...bundle.inputData }
}
NB : the spread operator raises a syntax error in Zapier code editor, but it works.

Zapier API Configuration: send form-data instead of json request body

I am setting up a Zap for our application in Zapier.
However, I've run into some trouble having the Zap pass over the data in the correct format.
By default it appears Zapier passes the data as json request body, but our backend only accepts form-data.
Is it possible to configure the Zap to send over form-data instead?
In the code below, I've tried to send the data as both params and body, but my backend doesn't any of it as form-data:
const options = {
url: '${URL}',
method: 'POST',
headers: {
'Authorization': ${token},
'Content-Type': 'application/json',
'Accept': 'application/json'
},
params: {
'phone': bundle.inputData.phone,
'email': bundle.inputData.email,
'dialog': bundle.inputData.dialog,
'name': bundle.inputData.name
},
body: {
'name': bundle.inputData.name,
'email': bundle.inputData.email,
'phone': bundle.inputData.phone,
'dialog': bundle.inputData.dialog
}
}
return z.request(options)
.then((response) => {
response.throwForStatus();
const results = z.JSON.parse(response.content);
// You can do any parsing you need for results here before returning them
return results;
});
Any input is greatly appreciated!
I fixed it by replacing 'Content-Type': 'application/json' with 'Content-Type': 'application/x-www-form-urlencoded'.

Pact verification: Failure/Error: expect(header_value).to match_header(name, expected_header_value)

Using pact to verify if the response header matches for the consumer and provider.
Running the pact verification on the provider side gives me the following error:
Failure/Error: expect(header_value).to match_header(name, expected_header_value)
Expected header "abc" to equal "xyz", but was nil
However, when I inspect if my response header, it gives me the expected value ("xyz").
Here is the sample pact file I'm trying to verify:
"interactions": [
{
"description": "a request to do something",
"request": {
"method": "get",
"path": "/example"
},
"response": {
"status": 200,
"headers": {
"abc": "xyz"
}
}
}]
I’m new to pact. Any help would be appreciated.
While this is an old post, I hope this will help anyone who views this.
I'm not familiar with ruby, however if your using a basic HTTP Rest request you need to add the accept headers on the 'withRequest' as well as the expected headers on the 'withRespondWith'. You can use Postman to view both request and response headers; JavaScript Example:
describe('When a request is made to get all <resources>', () => {
beforeAll(() =>
provider.setup().then(() => {
provider.addInteraction({
uponReceiving: 'a request to receive to receive all...',
withRequest: {
method: 'GET',
path: '/<resource>',
// Default headers from Axios documentation
headers: { Accept: "application/json, text/plain, */*" }
},
...
willRespondWith: {
// expected headers
headers: { "Content-Type": "application/json; charset=utf-8" },
...

Parsing params that includes json string in rails controller

In a react-native app, I have the following post request that goes to a rails controller
fetch(POST_PAID_UP, {
method: 'POST',
body: JSON.stringify({
receipt_num: 127,
}).replace(/{|}/gi, "")
})
In the appropriate action of my rails controller I can examine params it looks like this;
{"\"receipt_num\":127"=>nil, "controller"=>"ios/accounts", "action"=>"create"}
so the data is being received. From params I need to extract the value of 'receipt_num'. I have tried JSON.parse(params), but I receive this error;
TypeError: no implicit conversion of Array into String
So how should I parse this data?
You need to add headers that indicate that the information being sent is of type json. So add the following hash to the fetch instruction;
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
You can then remove the .replace(/{|}/gi, "") which is just a work around to overcome the fact that you were not specifying the data was json. The final code should look like this:
fetch(POST_PAID_UP, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
receipt_num: transactionIdentifier,
})
})
You can find more information about fetch here

How to send JSON to MVC API (using Ajax Post)

I am trying to post some data using Ajax, but it is not getting through when using content type of application/json (HTTP/1.1 406 Not Acceptable), however if I change the content type to 'application/x-www-form-urlencoded' then it does work.
Any ideas?
Ajax code extract:
$.ajax({
type: "POST",
data: {"hello":"test"},
url: "http://workingUrl/controller",
contentType : 'application/json',
cache: false,
dataType: "json",
.....
Web API 2:
public IHttpActionResult Post(testModel hello)
{
/// do something here
}
Model:
public class testModel
{
public string hello {get;set;}
public testModel()
{ }
}
Fiddler:
HTTP/1.1 406 Not Acceptable (In the IDE, I have a breakpoint in the Post method which is not hit).
I have tried adding a formatter to WebAPi.config, but no luck
config.Formatters.Add(new JsonMediaTypeFormatter());
Try with this JSON.stringify(TestData) as shown below -
var TestData = {
"hello": "test"
};
$.ajax({
type: "POST",
url: "/api/values",
data: JSON.stringify(TestData),
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
success: function (data, status, jqXHR) {
console.log(data);
console.log(status);
console.log(jqXHR);
alert("success..." + data);
},
error: function (xhr) {
alert(xhr.responseText);
}
});
Output -
I've never specified contentType when I've done this and it's always works. However, if it works when you use 'application/x-www-form-urlencoded' then what's the problem?
I do see a couple thing off in your ajax. I would do this
$.ajax({
type: "POST",
data: {hello:"test"},
url: "http://workingUrl/controller/Post",
cache: false)}
For data, maybe quotes around the variable name will work but I've never had them there.
Next, the url in the ajax call doesn't have the name of your controller action. That needs to be in there.

Resources