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);
}```
Related
How do I transmit a pdf file? I have found multiple ways online, but most of them involve a rework of how our current system works, which is far from ideal.
Im not too familiar with angular, but I am trying to upload a file to the server. i am using existing architecture, so the issue isnt as easy as simply rewriting it from the ground up. Spring complains that "The current request is not a multipart request", if i try to send it as a multipart file, but I dont know how to make it one. The file type must be of type Blob. Currently, no error is thrown, but data.content is empty after the data block is transmitted.
Here is what I currently have:
$scope.uploadPDF = function(uploadedPDF) {
var url = 'uploadPDF';
data = {};
data.comments = $scope.worksheet.comments;
data.queryId = $scope.qId;
data.responseId = $scope.responseId;
data.requestTS = new Date().getTime();
data.content = uploadedPDF;
$http.post(url, data);
};
and the function that calls it is this, it pulls in the file, generates a name and adds the name as a property to be handled serverside, does some unaffiliated logic, then calls the above function for transmission:
$scope.addPDF = function() {
var pdfUploads = document.getElementById('file');
if ('files' in pdfUploads)
{
if (pdfUploads.files.length == 0)
{
$scope.setReasonForChange("addPDF");
}else
{
for (var i = 0; i < pdfUploads.files.length; i++)
{
var currentTimeZone = new Date().toLocaleTimeString('en-us',{timeZoneName:'short'}).split(' ')[2];
$scope.militaryTime = $filter('date')(Date.now(), "MM-dd-yyyy_HHmm");
pdfUploads.files[i].generatedFileName = "QID-" + $scope.queryId + "_" + $scope.worksheet.response.PDF_DESCRIPTION + "_" + $scope.militaryTime + currentTimeZone + ".PDF";
}
}
}
var pdfComment = document.getElementById("pdfComment").value;
if (!pdfComment)
{
$scope.setReasonForChange("updatePDF");
} else
{
var blobPDF = new Blob([pdfUploads.files[0]], {type: 'application/pdf'});
$scope.uploadPDF(blobPDF);
}
}
HTML is:
<form name="UploadForm" id="UploadForm" class="details" form-on-change="formChanged()" enctype="multipart/form-data">
<input type="file" multiple size="50" id="file" name="file" ng-disabled="is_readonly"/>
<button ng-click="addPDF()" ng-disabled="is_readonly">Add</button>
</form>
And lastly, serverside is this, where i think data is part of a linkedhashmap, where the values are taken from in the server, and processed:
#ResponseBody
#RequestMapping(value = "/uploadPDF", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseAttachment uploadPDF(#RequestBody Data data, HttpServletRequest request) throws Exception {
User user = (user) request.getSession(false).getAttribute(FieldConstants.USER_SESSION_ATTR);
ResponseAttachment newPDF = responseAttachmentService.addAttachment(data, user.getUserId());
return newPDF;
Currently, it transmits and receives the data, except the place where the file is supposed to be is empty.
I have attempted ng-fileupload, but attaching it to our product is a nightmare, especially considering that its use kinda requires the user to already know how to use angular as it has little documentation... and we have no angular people.
This question may help you.
Basically you can't send files in purely a JSON format. You have to use a multipart form and post it that way. For example:
postFile(file) {
var postData = new FormData();
postData.append('File', file);
var params = {
headers: {
"Content-Type": undefined
}
$http.post(url, data, params).then([...]);
}
You'll need the extra Content-Type param so that it is sent properly.
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;
});
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.
As it is, ExtJS 4.1 with a Rest proxy and a Json reader asks for a URI like this (urlencoded, though):
http://localhost:8000/api/v1/choice/?filter=[{"property":"question_id","value":2}]
my server wants filter requests to look like:
http://localhost:8000/api/v1/choice/?question_id=2
I've looked at the filterParam config for the proxy, but it doesn't seem relevant. Is there a practical way to achieve the request URI that the server needs?
Following ain't pretty, but it works. Now to fix the damn Store...
/**
* Customized to send ../?prop=val&prop2=val2 urls.
*/
buildUrl: function(request) {
var url = this.url;
var filters = eval(request.params['filter']);
if (filters) {
delete request.params['filter'];
url += '?'
for (var i = 0; i < filters.length; i++) {
var filterString = filters[i].property + "=" + filters[i].value;
if (url.slice(url.length-1) === '?') {
url += filterString;
} else {
url += '&' + filterstring;
}
}
};
return url;
},
There is no simple (easy) way. You will have to extend existing Proxy class. Take a look at the source code for Ext.data.proxy.Proxy and Ext.data.proxy.Server. Start with looking at functions getParams and buildUrl
I'm having a great deal of difficulty with this - I seem to be going in circles.
What I'm trying to do is POST data to a web service from a javascript on a client.
in the examples below, valFname, valLname, valPhone, and valZip all have valid string values:
function checkOffers(){
// data collection from loaded form...
var postData = "'FirstName':'" + valFname ;
postData +="','LastName':'" + valLname ;
postData +="','PhoneNumber':'" + valPhone ;
postData += "','Zipcode':'" + valZip+"'";
initialize(postData);
}
function initialize(postData) {
//var postMsg = createSoapHeader(msg);
var url = "https://server.company.com:9999/analytics/webservices/webservice.asmx/SamplePriorityOfferList";
request.open("POST", url, false)
request.onreadystatechange = function(){
if(this.readyState===4){
//request is complete. handle it
processData;
}
};
request.send(postData);
}
function processData(){
response = request.responseXML.xml;
alert("Returned Data:" + response);
}
I am calling the checkOffers function on the PageLoad event - I want the web service to fire without having to click a button, link, etc.
I'm getting nulls back from my request, but should be getting data.
Any comments, tips, or suggestions are greatly appreciated.
This line:
if(this.readyState===4){
should be:
if(this.readyState==4){
That should at least get you seeing the alert.