Fiddlerscript to send a modified request to the server wont work - javascript

Ive created a fiddlescript rule that I thought would wait for a specific object:value, automatically send the a portion of the json value back to a different URI as a post request with the same header information such as cookies.
When the script is activated I receive an error. I assume its something to do with the json object value.
static function OnBeforeResponse(oSession: Session) {
if (oSession.oResponse.headers.ExistsAndContains("Content-Type", "application/json")) {
oSession["ui-backcolor"] = "blue";
oSession.utilDecodeResponse();
}
if (oSession.oResponse.headers.ExistsAndContains("Content-Type", "application/json") && oSession.utilFindInResponse("faceId", false) > -1) {
oSession["ui-backcolor"] = "green";
oSession.utilDecodeResponse();
var oBody = System.Text.Encoding.UTF8.GetString(oSession.requestBodyBytes);
var j = Fiddler.WebFormats.JSON.JsonDecode(oBody);
var facId = j.JSONObject["faceId"];
var reqBod = '{"faceId":"' + facId + '"}';
oSession.oRequest.headers.HTTPMethod == "POST";
oSession.utilSetRequestBody(reqBod);
oSession.url = "https://urltosendpostrequest.com/Search";
FiddlerObject.utilIssueRequest(oSession);
}
I expected the server to accept the modified POST request but instead the script runs into an error.
FiddlerScript OnBeforeResponse0 failed. X
There was a problem with your FiddlerScript.
Function expected Function expected at Microsoft.)Script.Latainding.CallValue(Object val, Objects arguments, Boolean construct, Boolean brackets, VsaEngine engine, Object thisob, Binder binder, Culturelnfo culture, Strings namedParameters) at Microsoft.JScript.Latainding.Call(Binder binder, Objects arguments, ParameterModifier]] modifiers, Culturelnfo culture, Strings namedParameters, Boolean construct, Boolean brackets, VsaEngine engine) at Microsoft.JScript.Latainding.Call(ObjectS arguments, Boolean construct, Boolean brackets, VsaEngine engine) at Fiddler.ScriptNamespace.Handlers.OnBeforeResponse(Session oSession) at Fiddler.ScriptBase. 1:1(Session OD) in CA.lenkins\Fiddler_Windows\workspace\Fiddler2\Common\Application\ Scripting\ScriptBase.csiline 921

You are mixing access to the request and the response header/body. Also it seems that it is not clear to you that the POST data belongs to the request not the response. Therefore make sure you are manipulating the correct data (the request or the response).
Or do you want to capture the request and send a custom response back to the client? If yes you should look at the AutoResponder Flag x-replywithfile.
You script has code in OnBeforeResponse therefore you can only access properties and methods that are related to the response.
However you have the following code which tries to access the request (which is of course impossible as the request has already been forwarded):
oSession.oRequest.headers.HTTPMethod == "POST";
oSession.utilSetRequestBody(reqBod);
FiddlerObject.utilIssueRequest(oSession);

Related

Mailgun in .xsjs

is there a way to send an email via Mailgun with html page as its content that is longer than ~2000 characters?
I have this code, that works perfectly for short html as I believe it is sent in URL address:
var obj = $.request.body.asString();
var req = new $.web.WebRequest($.net.http.POST, "/messages");
req.headers.set('Content-Type', encodeURIComponent("application/x-www-form-urlencoded"));
req.parameters.set("domain", "mailgundomain.com");
req.parameters.set("from", "me#mailgundomain.com");
req.parameters.set("to", 'to#email.com');
req.parameters.set("subject", "subject");
req.parameters.set("html", obj); //email content
In the code above I receive the file and save it to 'org' variable and then send it to mail. What I need is to probably get my "too large" .html file to the body and then show it as a content of the email. As you probably can see, I'm quite new in .xsjs so the more detailed answer the better. If you need any more info, feel free to ask. Thank you.
Edit1: I should add that when I try to send a larger file, the response I get is "414 Request-URI Too Large".
EDIT
This seems to be the right approach, jointly figured out by the OP and myself:
var obj = $.request.body.asString();
var req = new $.web.WebRequest($.net.http.POST, "/messages");
// request headers
req.headers.set('Content-Type', "application/x-www-form-urlencoded");
// request URL parameters
req.parameters.set("domain", "mailgundomain.com");
req.parameters.set("from", "me#mailgundomain.com");
req.parameters.set("to", 'to#email.com');
req.parameters.set("subject", "subject");
// request body
req.setBody(encodeURIComponent(message));
The $.web.WebRequest class sends everything you set in the .parameters collection as an URL parameter, even if the request method is POST. This is perfectly all-right, POST requests may have URL parameters. However, URLs are length-limited, as you have noticed.
The body of a POST request is not length-limited, but you have to do the proper content encoding on your own. The body of a application/x-www-form-urlencoded type request follows the same rules as the URL - key=value pairs separated by & characters.
var obj = $.request.body.asString();
var req = new $.web.WebRequest($.net.http.POST, "/messages");
req.headers.set('Content-Type', "application/x-www-form-urlencoded");
var message = {
domain: "mailgundomain.com",
from: "me#mailgundomain.com",
to: "to#email.com",
subject: "subject",
html: obj
};
req.setBody(urlEncode(message));
where urlEncodedFormat() is a little helper function:
function urlEncode(obj) {
return Object.keys(obj).map(function (key) {
return encodeURIComponent(key) + "=" + encodeURIComponent(obj[key]);
}).join("&");
}
Turning objects into an URL-encoded string is a pretty common operation. It's likely that one of the libraries you use already contains a function that does that.
While the above function is is probably correct (there might be edge cases with undefined or null values), it's preferable not to use a hand-rolled variant. Spend some time looking for the right function in your libraries.
Maybe WebRequest already does the right thing on its own, I have no way to test it, though. Try setting the message object as the body directly:
req.setBody(message);

Accessing a Javascript variable inside an HTML file

I'm doing a little bit of reverse engineering on the Rapportive API in Gmail.
I make this request
import requests
url ='https://api.linkedin.com/uas/js/xdrpc.html'
r = requests.get(url)
print r.text
The response is an empty HTML file that has a lot of Javascript in it. On line 3661, it sets the RequestHeader for the subsequent call to Rapportive:
ak.setRequestHeader("oauth_token", ae);
Is there a way I can request that page and then return ae?
I think you can try:
Get the page as you already does;
Remove all non-javascript elements from the response page;
Prepend a javascript (described below) in the page's javascript to override some code;
Execute it with eval('<code>');
Check if the token has been set correctly;
I'm proposing the following code to override the XMLHttpRequest.setRequestHeader functionality to be able to get the token:
// this will keep the token
var headerToken;
// create a backup method
XMLHttpRequest.prototype.setRequestHeaderBkp =
XMLHttpRequest.prototype.setRequestHeader;
// override the "setRequestHeader" method
XMLHttpRequest.prototype.setRequestHeader = function(key, val)
{
if ('oauth_token' === key)
headerToken = val;
this.setRequestHeaderBkp(key, val);
}
If you are just interested in retrieving the token can't you just do a regex match:
var str = '<script>var a = 1;...ak.setRequestHeader("oauth_token", ae);...</script>';
var token = str.match(/setRequestHeader\("oauth_token",\s*([^)]+)/)[1];
Although this assumes ae is the actual string value. If it's a variable this approach wouldn't work as easily.
Edit: If it's a variable you could do something like:
str.replace(/\w+\.setRequestHeader\([^,]+,\s*([^)]+)\s*\);/, 'oauthToken = \1';
Before running the JavaScript returned from the page, then the global oauthToken (notice the missing 'var') will contain the value of the token, assuming the the evaluation of the code is run in the same scope as the caller.

Retrive post data back using javascript/jquery

I want to pass the object to the new page by using only client side script(javascript),
and I want to read the data back when the new page is loads, but I could not find any tutorial or method to get it.
function postToURL(path, parameters) {
var form = $('<form></form>');
form.attr("method", "post");
form.attr("action", path);
$.each(parameters, function(key, value) {
var field = $('<input></input>');
field.attr("type", "hidden");
field.attr("name", key);
field.attr("value", value);
form.append(field);
});
// The form needs to be a part of the document in
// order for us to be able to submit it.
$(document.body).append(form);
form.submit();
}
The POST message sent to the server to retrieve the current page is not exposed, by the browser, to JavaScript in that page, so you cannot.
Pass the data via some other technique (such as through the URL, or localstorage).
Yeah, POST data is only handled and seen by the server side (ex. PHP). Javascript is on the client side so it will never be able to see that data unless the POST data first gets passed to server side and that server side in turn hands it off to the client side (ex. Javascript).
Consider using GET as your method in your code above so that you can pass the parameters inside the actual URL to make it accessible to the browser / client / Javascript.
parameters can be parsed from a JSON-encoded string. If you build your parameters programmically (in the previous step) like:
parameters = {};
parameters['USA'] = 'Washington DC';
parameters['UK'] = 'London';
You can create a flat JSON String representing your structured data by:
parametersString = JSON.stringify(parameters);
and end up with something like this:
"{'USA': 'Washington DC', 'UK': 'London'}"
You can store this string in a cookie, or in a query string or fragment part of the URL.
Your next page can read back this value on the following page, and re-create the structured parameters by decoding the JSON string like:
parameters = JSON.parse(parametersString);
and you're getting the original data back, on which you can run JQuery's each.

How to pass in a JSON object to a resource in angularjs

I would like to use a web-service that takes in JSON object (The object binds two arrays) in a POST request and returns a JSON object array.
I would now like to send request to the webservice from my AngularJS. Here is my code:
wellApp.factory('Search', ['$resource',function($resource){
return $resource('/filetables/searchdata/:tagSearchInput',
{
},
{
searchData:{
method:'POST',
isArray: true,
params:{ tag: '#tagSearchInput.tag',
details: '#tagSearchInput.details'
}
}
})
}])
function myWellsCtrl($scope,$resource, Wells, Tags, Search) {
$scope.wellSearchResult = Search.searchData({tag: ["TypeOfWell"],
details: ["Vertical"]});
};
If I do this, I get a NullPointerException at the server side, meaning that the arguments that I pass are getting passed as null.
How do I pass in this object such that the server interprets them as an object containing two arrays. I'm new to AngularJS and am not able to understand the # notation of assigning the incoming parameter. It'd be great if someone here can lend me some help.
You shouldn't need to include params in searchData since the JSON will be sent in the body of the POST request. Try removing them from searchData. Then in your controller, try calling your service like this:
Search.searchData({}, {tag: ["TypeOfWell"], details: ["Vertical"]})
Note the {} as the first parameter, which is the params for your request. The second {} is for the payload. This will send your JSON in the request payload instead of as params. Let me know if that doesn't work for you. I have done something similar to what you're doing and this way worked for me.
You didn't mention which server side you are using. But, the first thing you probably need to do is set the HTTP Header content type. I usually set it globally on the $http object, like this:
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
With the default content-type header, the form parameters are not attached to the request as form parameters and they cannot be accessed as form parameters on the server side code.
Second, this:
{
tag: '#tagSearchInput.tag',
details: '#tagSearchInput.details'
}
is not a valid JSON object. The property names must be enclosed in double quotes. Here they are enclosed in none. The property values must also be enclosed in single quotes; here they are enclosed in single quotes.
I believe that should be a valid JavaScript object; but it isn't JSON. You can tweak it here:
{
"tag": "#tagSearchInput.tag",
"details": "#tagSearchInput.details"
}
I wrote up a blog post about my experiences integrating AngularJS with ColdFusion. What I have been doing is converting my objects to JSON Strings before passing them over the wire. Then the server side will deserialize the JSON string.
Here is a great post, similar to mine, that is PHP focused.

I need some assistance with PHP and updating the URL after a "?"

Hi so I have a project for class that is a mix of PHP, HTML, and javascript/Ajax.
One of the requirements is "Execute program.php on server passing it the N/V pairs following the "?" symbol." How do I do this?
First off.. I don't know what NV pairs are and the reading links we were given say nothing about them.. I Googled "Php nv pairs" and literally nothing relative comes up.
I did an in-class activity that upon clicking a button, the url would update and add stuff after the "?" but of course that same code isn't doing it anymore. My professor is terrible at explaining anything and leaves us to follow his typo instructions that aren't even complete..
Here's the code we were given with his comments trying to explain what to do:
// startgame function
// sart button pressed check fields, if OK send to PHP via get request
function startgame(){
//Create the XMLHttpRequest Object
var xmlhttp;
// error handling
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
xmlhttp = false;
}
}
http = xmlhttp;
// The PHP server script, called with N/V pair with GET request
// Using get request the NV pairs follow "?"
// execute program.php on server passing it the n/v pairs
// that follow the "?"
var url = "program.php?player1name=";
// for this example, only pass to PHP games played
// "&" separates n/v pairs
// player1name is name of algorithm player 1 is using
player1name = document.JForm.p1name.value;
player2name = document.JForm.p2name.value;
gamesplayed = document.JForm.gamesplayed.value;
sdata = url+player1name+"&gamesplayed="+gamesplayed;
// for a "real" solution, pass more data to PHP about state of game
// send get request to server with n/v pairs of screen data
http.open("GET",sdata, true);
// register with server what function to return data
http.onreadystatechange = handleHttpResponse;
// send request to server
http.send(null);
}
Anything will help, thanks!
NV apis means "Name/Value pairs". Basically, in the terms you will be using them in, it is a key connected to its value with an equal sign. For example: username=johnconde. username is the key and johnconde is the value. An example more closely related to your code would be gamesplayed=20. gamesplayed is the key and 20 is the value.
Name/value pairs are commonly found in query strings and it looks like that's what you need to do with your code. You need to build a query string comprised of name/value pairs containing the values you need for your PHP script to do whatever it is it needs to do. It looks like the code already does this and you just need to build the form necessary for this JavaScript to work.

Categories

Resources