Access invocation URL in Swagger UI - javascript

In a custom JavaScript file in Swagger-UI I was trying to access the request URL because I needed to add it to a header before I submit the request.
After looking at the source for swagger UI, I've not been able to figure out how to access the request URL.
In a my custom JavaScript file I've cheated by stealing from the DOM using:
(function() {
$(function() {
$(".submit").click(function (e) {
// doesn't work
// log(SwaggerUi.Views.OperationView.invocationUrl);
var url = $($(this).parentsUntil(".operations")[3]).find(".path")[0].innerText;
log("URL: " + url);
});
});
})();
But being this is a hack, it will not work if the route had a parameter like so: url/{param}. To find the input param and replace would be another step I would rather not take.
Am I missing some easy way that would allow me to access the request URL something along the lines of: SwaggerUi.requestUrl

Devised solution to traverse the DOM to get the information needed instead of using the information being stored by Swagger-UI.
(note: using the embedded Swagger-UI given by Swashbuckle 5.4 your mileage may vary if you use a different version of Swagger-UI)
$(".submit").click(function (e) {
var originalUrl = $($(this).parentsUntil(".operations")[3]).find(".path")[0].innerText;
log(originalUrl);
var outputUrl = "";
$($(this).parentsUntil(".operations")[3])
.find("tbody.operation-params tr:contains('path')")
.find("input")
.each(function () {
var pathParam = $(this).attr('name');
log(pathParam);
var userInput = $(this).val();
log(userInput);
outputUrl = originalUrl.replace("{" + pathParam + "}", userInput);
log(outputUrl);
});
// final requestUrl or invocationUrl
var requestUrl = $(".footer h4").html().match(/: (\/[\w-]+)/)[1] + outputUrl;
});

Related

JS - Intercept attribute changes

My goal here is to intercept all attribute setting and changes. Problem is that I don't know how to do that. I wanna change attributes that set / change like this
cpo.src = "/cdn-cgi/challenge-platform/orchestrate/jsch/v1"; not using setAttribute(src, 'stufz')
I have some code that could be used from my Ajax interceptor that works 100% and changes the request. Basically why I am doing this is I am making a web proxy and it needs great rewriting. Please client-side JS only! Pure Javascript too!
Basically heres an example of how I wanna intercept it
/cdn-cgi/challenge-platform/orchestrate/jsch/v1 --> /alloy?url=https://soap2day.to/cdn-cgi/challenge-platform/orchestrate/jsch/v1
If I am not being clear enough please explain in the comments.
// Ajax Interceptor that works perfectly that could be used in this case.
let oldXHROpen = window.XMLHttpRequest.prototype.open;window.XMLHttpRequest.prototype.open = function(method, url, async, user, password) {
if (url.startsWith('http')) {
const encodedURL = btoa(url)
url = '/alloy/?url=' + encodedURL
} else if (url.startsWith('//')) {
const encodedURL = btoa('http:' + url)
url = '/alloy/?url=' + encodedURL
} else if (url.startsWith('/')) {
if (!url.startsWith('/fetch/')) {
let apData = document.getElementById('alloyData');
let urlData = apData.getAttribute('data-alloyURL');
url = '/fetch/' + urlData + url
}
}
return oldXHROpen.apply(this, arguments);
}```

How to pass FormData over XMLHttpRequest using GET method

When Method of the senderform is POST, everything works fine. However, as soon as I change the method to GET, I don't receive anything on the server.
function ajaxSubmit(destinationElement, senderform) {
var xmlreq = new XMLHttpRequest();
var params = new FormData(senderform);
xmlreq.open(senderform.method, senderform.action, true);
if (/\/content\.php$/.test(senderform.action))
xmlreq.onreadystatechange = receiveTable;
else xmlreq.onreadystatechange = receiveText;
xmlreq.send(params);
}
I know that I could manually append key-value pairs at the end of Action address, but the problem is that I don't know which form is going to be passed with what fields.
I would prefer native javaScript if possible.
How can I send a GET request using XMLHttpRequest with key-value pairs from senderform which points to form Element (the same way as it already works for POST requests)?
First parameter is a reference to submit button, or form element itself. Second is callback function for XMLHttpRequest.
var ajaxSubmit = function(sender, callback) {
var xmlreq = new XMLHttpRequest(), params;
// look around for the sender form and key-value params
if (sender.form !== undefined)
{
params = new FormData(sender.form);
params.append(sender.name, sender.value);
sender = sender.form;
}
else params = new FormData(sender);
var actAddress = sender.action;
// append the params to the address in action attribute
if (sender.method == 'get')
{
var firstRun = true;
for (var key of params.keys())
{
if (firstRun)
{
actAddress += '?';
firstRun = false;
}
else actAddress += '&';
actAddress += key + "=" + params.get(key);
}
}
xmlreq.open(sender.method, actAddress, true);
xmlreq.onreadystatechange = callback;
if (sender.method == 'get')
xmlreq.send();
else xmlreq.send(params);
}
Therefore you can use it as
<form onsubmit="ajaxSubmit(this,callbackFx)" >
<!-- or -->
<input onclick="ajaxSubmit(this,callbackFx)" type="submit" name="" value=""/>
</form>
Are you sure the problem is not the PHP script? I see no reference that https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#send() with FormData needs POST to work, but if the PHP script takes the info from $POST or something (My PHP is rusty), the behavior would be different.
Since you can't create a useable body in a GET request (see below), then the other option is to use params in the url.
function buildGetUrlParams(baseUrl, paramsObj) {
var builtUrl = baseUrl + "?";
Object.keys(paramsObj).forEach(function(key) {
builtUrl += key + "=" + paramsObj[key] + "&";
});
return builtUrl.substr(0, builtUrl.length - 1);
}
document.getElementById('finalUrl').innerText = buildGetUrlParams('http://test.url.com', { name:'James', occupation:'web design' });
<div id="finalUrl"></div>
An HTTP GET request can contain a body, but there is no semantic meaning to that body. Which means, in simple terms, that a server doesn't have any reason to, nor have any knowledge of how, to process the body of a GET request. If it's possible to write a server that could do this, it would be bad practice as per the HTTP/1.1 specs:
if the request method does not include defined semantics for an entity-body, then the message-body SHOULD be ignored when handling the request.
And that's basically why it's not working. If you want to send any sort of data that the server is able to respond to, then you'll need to use a different HTTP method.
This answer also explains this issue.

Twitter API - no encoding

I'm currently working on a project for university. we are trying to use the twitter api but we are having some trouble with the query. I want to search a complete string, therefore I need to put my string in quote sings.( like "I'm seraching for this whole sting")
the problem is that the command I use to get the array from twitter somehow encodes the whole string but I need the quote sings to not be encoded. I hope you guys understand my problem. in addition i'll post my js code.
JS CODE: first I tryed a json command but it didnt work. afterwards I tryed ajax but I ran into the same problem. I don't get a response when I use quote signs in my query.
$( document ).ready(function()
{
console.log("ready");
// div mit id unique1 - bei klick mache onClick1
$('a#unique1').bind('click', onClick1);
});
function onClick1(elem)
{
var inputString = $("#SearchInput").val();
var EncodedString = encodeURI(inputString);
console.log('test' + inputString);
var endNode = 'search/tweets.json?q=hate%20' + EncodedString + '&result_type=mixed&count=200';
/*
$.getJSON('twitter/twitter-proxy.php?url='+encodeURIComponent(endNode),
*/
$.ajax({
type: "GET",
url: 'twitter/twitter-proxy.php?url='+encodeURIComponent(endNode),
data: " ",
success: function(twitterResponse){
var respStr = "start";
console.log(twitterResponse);
console.log(twitterResponse.statuses);
for(var i = 0; i < twitterResponse.statuses.length; i++)
{
$('.container .apiCall ol').append('<li>'+ twitterResponse.statuses[i].created_at + '</br>' + twitterResponse.statuses[i].text.toLowerCase() + '</li>');
respStr = respStr + twitterResponse.statuses[i].created_at + twitterResponse.statuses[i].text.toLowerCase();
}
}
});
/*
function(twitterResponse)
{
var respStr = "start";
console.log(twitterResponse);
console.log(twitterResponse.statuses);
for(var i = 0; i < twitterResponse.statuses.length; i++)
{
$('.container .apiCall ol').append('<li>'+ twitterResponse.statuses[i].created_at + '</br>' + twitterResponse.statuses[i].text.toLowerCase() + '</li>');
respStr = respStr + twitterResponse.statuses[i].created_at + twitterResponse.statuses[i].text.toLowerCase();
}
*/
/*
// respSgtr = " ";
// write tweets to file
$.post("writer.php", { fileString:respStr},
function(response)
{
//alert("Data Loaded: " + data);
});
});*/
}
Your approach is flawed.
jQuery does all the parameter encoding for you. Don't interfere, just pass an object which contains keys and values. Do not build URLs from individual bits of string.
Important security consideration: Don't build a server-side proxy script that accepts any arbitrary URL. Doing this is plain stupid.
Instead change your PHP script to accept a set of operation verbs, like "search", which are hard-wired to the correct URL on the server side.
I recommend using $.get() and $.post() over $.ajax(), for the benefit of cleaner code.
Further, use $.each() rather than a regular for loop. The resulting code will be cleaner and easier to read.
Avoid building HTML from bits of string. Especially if the bits of string come from a completely untrustworthy source, like Twitter. Use jQuery's capabilities and the DOM to build HTML safely. (read about XSS vulnerabilities if you're not sure why I bring this up)
Suggested solution (appendText() jQuery plugin taken from here):
$.fn.appendText = function(text) {
return this.each(function() {
var textNode = document.createTextNode(text);
$(this).append(textNode);
});
};
$(function () {
$('a#unique1').on('click', function (event) {
$.get('twitter/twitter-proxy.php', {
operation: 'search',
params: {
q: 'hate ' + $("#SearchInput").val(),
result_type: 'mixed',
count: 200
}
}).done(function (twitterResponse) {
$.each(twitterResponse.statuses, function (index, status) {
$("<li>")
.appendText(status.created_at)
.append("<br>")
.appendText(status.text.toLowerCase())
.appendTo(".container .apiCall ol");
});
});
});
});

Google Analytics - Using GET instead of POST

Ran into an issue where I need to use GET vs POST on a form method, but GATC cookie data is not being appended to the URL correctly, because the form's data is trumping Google's GATC data (using linkByPost).
I've read up on a potential solution posted here, but seems like an insane amount of work to make GET behave. I also stumbled upon another solution here, but IE doesn't respect anything after the 'anchor' portion of the url.
Anyone have any other ideas? If I can't handle this via JS, I will have to go into the script handling the form action and massage the querystring manually (assuming that GATC data is in $_REQUEST array). FTR, GATC data is not available via the $_REQUEST array, when using get.
For future reference, in case anyone runs into the same issue, this is the solution I implemented. I lifted some code from the answer to this SO post, and combined it with the idea behind this post, where it localizes the GATC data, and adds hidden fields to the form for each one.
Resulting code:
$(document).ready(function() {
$('#formId').submit(function(e) {
try {
e.preventDefault();
var form = this;
if (typeof _gat !== 'undefined') {
_gaq.push(['_linkByPost', this]);
var pageTracker = _gat._getTrackerByName();
var url = pageTracker._getLinkerUrl(form.action);
var match = url.match(/[^=&?]+\s*=\s*[^&#]*/g);
for ( var i = match.length; i--; ) {
var spl = match[i].split("=");
var name = spl[0].replace("[]", "");
var value = spl[1];
$('<input>').attr({
type: 'hidden',
name: name,
value: value
}).appendTo(form);
}
}
setTimeout(function() { form.submit(); }, 400);
} catch (e) { form.submit(); }
});
});
You can use jQuery serialize to get the form's elements, then _getLinkerUrl to append the cross-domain tracking data
$('#formID').submit(function(e) {
var pageTracker = _gat._getTrackerByName();
var url = this.action + '?' + $(this).serialize();
url = pageTracker._getLinkerUrl(url);
if (this.target != '_blank') location.href = url;
else window.open(url);
});

jQuery getJSON never enters its callback function

I've been sitting with this for hours now, and I cant understand why.
q is working. The URL does give me a proper JSON-response. It shows up as objects and arrays and whatnot under the JSON tab under the Net-tab in Firebug and all is fine. I've also tried with other URLs that i know work. Same thing happens.
I have another function elsewhere in my tiny app, wihch works fine, and is pretty much exactly the same thing, just another API and is called from elsewhere. Works fine, and the data variable is filled when it enters the getJSON-function. Here, data never gets filled with anything.
I've had breakpoints on every single line in Firebug, with no result. Nothing happens. It simply reaches the getJSON-line, and then skips to the debugger-statement after the function.
var usedTagCount = 10;
var searchHits = 20;
var apiKey = "a68277b574f4529ace610c2c8386b0ba";
var searchAPI = "http://www.flickr.com/services/rest/?method=flickr.photos.search&" +
"format=json&api_key=" + apiKey + "&sort=interestingness-desc&per_page="
+ searchHits + "&jsoncallback=?&nojsoncallback=1&tags=";
var tagString = "";
var flickrImageData = new Array();
function search(query) {
for(var i = 0; i < usedTagCount; i++) {
tagString += query[i].key + ",";
}
var q = searchAPI + tagString;
$.getJSON(q, function(data) {
debugger; /* It never gets here! */
$.each(data.photos.photo, function(i, item) {
debugger;
flickrImageData.push(item);
});
});
debugger;
return flickrImageData;
}
Example of request URL (q):
http://www.flickr.com/services/rest/?method=flickr.photos.search&format=json&api_key=a68277b574f4529ace610c2c8386b0ba&sort=interestingness-desc&per_page=20&jsoncallback=?&tags=london,senior,iphone,royal,year,security,project,records,online,after,
I do wonder, since JSONView (the firefox plugin) cannot format it properly, that it isn't really JSON that is returned - the mime-type is text/html. Firebug, however, interprets it as JSON (as i stated above). And all the tag words come from another part of the app.
I think you might need to remove the
nojsoncallback=1
from your searchAPI string.
Flickr uses JSONP to enable cross domain calls. This method requires the JSON to be wrapped in a json callback, the nojsoncallback=1 parameter removes this wrapping.
EDIT: Apparently it works with nojsoncallback=1, I got this piece of code to work for me. What jQuery version are you using? JSONP is only available from 1.2 and up.
This works for me (slight modifications):
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
var usedTagCount = 1;
var searchHits = 20;
var apiKey = "a68277b574f4529ace610c2c8386b0ba";
var searchAPI = "http://www.flickr.com/services/rest/?method=flickr.photos.search&" +
"format=json&api_key=" + apiKey + "&sort=interestingness-desc&per_page="
+ searchHits + "&jsoncallback=?&nojsoncallback=1&tags=";
var tagString = "";
var flickrImageData = new Array();
function search(query) {
tagString = query;
var q = searchAPI + tagString;
$.getJSON(q, function(data) {
$.each(data.photos.photo, function(i, item) {
debugger;
flickrImageData.push(item);
});
});
}
search("cat");
</script>
When I try the url: http://www.flickr.com/services/rest/?method=flickr.photos.search&format=json&api_key=a68277b574f4529ace610c2c8386b0ba&sort=interestingness-desc&per_page=10&tags=mongo
it returns data, as it should -
try to change the getJSON to an $.ajax() and define a function jsonFlickrApi (data)
with the code you have in you callback function.
If that don't work - please post code to at jsbin.com <- so we can try it live - so much easier to debug.

Categories