Intercept outgoing HXR requests and their content - javascript

I am looking to monitor all outgoing HXR requests on the page in order to intercept a specific one that I wish to extract its data to log.
Here's the specific request I am trying to intercept:
Request header from the console
Request body I want to extract
Here's what I tried so far:
(function(send) {
XMLHttpRequest.prototype.send = function(body) {
var info="send data\r\n"+body;
console.log(info);
send.call(this, body);
};
})(XMLHttpRequest.prototype.send);
This seems to be somehow working because I get some requests logged in the console but not the ones I am looking for.
I also get some send data [object FormData] logged.
I am probably missing something about which HXR requests I am intercepting with my script and would love some help!
Thanks for your time!

This may just be the reason for the implicit conversion, you can try the JSON.Stringify(body) method.

Related

CKEditor change in ajax URL ?t=timestam to ?open&t=timestamp

I use the CKEDITOR on my HTML page, but I can not connect it properly, my WEB server does not understand such requests and I need to change them.
My WEB server does not support requests like ?t=timestamp.
How can I change this, for example, to have ?Open&t=timestamp.
I have the following requests:
GET http://mysite.ru/webadmin/ckeditor/config.js?t=H4PG 400 (Bad Request)
GET http://mysite.ru/webadmin/ckeditor/skins/moono-lisa/editor.css?t=H4PG (Bad Request)
GET http://mysite.ru/webadmin/ckeditor/lang/ru.js?t=H4PG 400 (Bad Request)
Should be so
GET http://mysite.ru/webadmin/ckeditor/config.js?open&t=H4PG
GET http://mysite.ru/webadmin/ckeditor/skins/moono-lisa/editor.css?open&t=H4PG
GET http://mysite.ru/webadmin/ckeditor/lang/ru.js?open&t=H4PG
How to set my suffix for all connected plug-ins?
It seems to me that there is some parameter that will allow you to insert your HTTP command after the question.
Example,
CKEDITOR.config.<param>="open&"
or callback function
function(request){
request+="open&";
}
How to do it?
Tried it like this
function CKEDITOR_GETURL( resource ){
var base="/webadmin/ckeditor/";
var r=resource;
if(!/^\//.test(r))r=base+r;
return r;
}
But some of the resources are not properly processed, a bad idea

How to get data from window.fetch() response?

I'm trying to use window.fetch() to get json from the server, but can't get the data from the response.
I have this code:
let url =
'https://api.flightstats.com/flex/schedules/rest/v1/json/from/SYD/to/MEL/departing/2016/3/28?appId=f4b1b6c9&appKey=59bd8f0274f2ae88aebd2c1db7794f7f';
let request = new Request (url, {
method: 'GET',
mode: 'no-cors'
});
fetch(request)
.then(function(response){
console.log(response)
});
It seems that this request is successfull, I see status 200
and response body with json in network tab - status and response. But in console.log I dont see json object - console log image
I cant understand why I dont see json in console.log
The host site you are requesting from does not appear to support CORS. As such, you can't use fetch() to make a cross origin request and get the data back. If, you change your fetch() request to mode: 'cors', the debug console will show that the host site does not offer CORS headers to allow the browser to show you the result of the request.
When you are using mode: 'no-cors', the browser is hiding the result from you (because you don't have permission to see it) and you can see the response is tagged as opaque.
In a little poking around on the api.flightstats.com site, I did see that it supports JSONP which will allow you to work around the lack of CORS support issue and successfully complete a cross origin request.
For simplicity of showing that it can work, I used jQuery to just prove that a JSONP request can be made. Here's that code in a working snippet. Note I changed the URL from /json/ to /jsonp/ and specific dataType: "jsonp" in the jQuery request. This causes jQuery to add the callback=xxxxx query parameter and to fetch the response via that corresponding script (the JSONP method).
var url =
'https://api.flightstats.com/flex/schedules/rest/v1/jsonp/from/SYD/to/MEL/departing/2016/3/28?appId=f4b1b6c9&appKey=59bd8f0274f2ae88aebd2c1db7794f7f';
$.ajax(url, {dataType: "jsonp"}).then(function(response) {
log(response);
}, function(err) {
log("$.ajax() error:")
log(err);
})
<script src="http://files.the-friend-family.com/log.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
If you take a look at the documentation of the Fetch API; you'll notice that the API offers various methods to extract the data:
arrayBuffer()
blob()
json()
text()
formData()
Assuming the response is valid JSON (which I've noticed it doesn't seem to appear), you can use the response.json() function to retrieve the response data. This also uses a Promise mechanism, as for everything with the Fetch API.
response.json().then(function(data) {
console.log(data);
});

How can we check if response for the request came from Service Worker

In Google Chrome console next to the status code of HTTP Request we have info (from ServiceWorker). Can Request be aware somehow that the Response came from ServiceWorker? Comparing date from Response Headers maybe?
By design, a response returned via a FetchEvent#respondWith() is meant to be indistinguishable from a response that had no service worker involvement. This applies regardless of whether the response we're talking about is obtained via XMLHttpRequest, window.fetch(), or setting the src= attribute on some element.
If it's important to you to distinguish which responses originated via service worker involvement, the cleanest way I could think of would be to explicitly add an HTTP header to the Response object that is fed into FetchEvent#respondWith(). You can then check for that header from the controlled page.
However, depending on how your service worker is obtaining its Response, that might be kind of tricky/hacky, and I can't say that I recommend it unless you have a strong use case. Here's what an (again, not recommending) approach might look like:
event.respondWith(
return fetch(event.request).then(function(response) {
if (response.type === 'opaque') {
return response;
}
var headersCopy = new Headers(response.headers);
headersCopy.set('X-Service-Worker', 'true');
return response.arrayBuffer().then(function(buffer) {
return new Response(buffer, {
status: response.status,
statusText: response.statusText,
headers: headersCopy
});
});
})
)
If you get back an opaque Response, you can't do much with it other than return it directly to the page. Otherwise, it will copy a bunch of things over into a new Response that has a an X-Service-Worker header set to true. (This is a roundabout way of working around the fact that you can't directly modify the headers of the Response returned by fetch().)

How to send data in request body with a GET when using jQuery $.ajax()

The service API I am consuming has a given GET method that requires the data be sent in the body of the request.
The data required in the body is a list of id's separated by hypen and could potentially be very large and thus it must be sent in the body otherwise it will likely foobar somewhere in the browsers/proxies/webservers etc chain. Note I don't have control over the service or API so please don't make suggestions to change it.
I am using the following jQuery code however observing the request/response in fiddler I can see that the "data" I am sending is ALWAYS converted and appended to the query string despite me setting the "processData" option to false...
$.ajax({
url: "htttp://api.com/entity/list($body)",
type: "GET",
data: "id1-id2-id3",
contentType: "text/plain",
dataType: "json",
processData: false, // avoid the data being parsed to query string params
success: onSuccess,
error: onError
});
Anyone know how I can force the "data" value to be sent in the body of the request?
In general, that's not how systems use GET requests. So, it will be hard to get your libraries to play along. In fact, the spec says that "If the request method is a case-sensitive match for GET or HEAD act as if data is null." So, I think you are out of luck unless the browser you are using doesn't respect that part of the spec.
You can probably setup an endpoint on your own server for a POST ajax request, then redirect that in your server code to a GET request with a body.
If you aren't absolutely tied to GET requests with the body being the data, you have two options.
POST with data: This is probably what you want. If you are passing data along, that probably means you are modifying some model or performing some action on the server. These types of actions are typically done with POST requests.
GET with query string data: You can convert your data to query string parameters and pass them along to the server that way.
url: 'somesite.com/models/thing?ids=1,2,3'
we all know generally that for sending the data according to the http standards we generally use POST request.
But if you really want to use Get for sending the data in your scenario
I would suggest you to use the query-string or query-parameters.
1.GET use of Query string as.
{{url}}admin/recordings/some_id
here the some_id is mendatory parameter to send and can be used and req.params.some_id at server side.
2.GET use of query string as{{url}}admin/recordings?durationExact=34&isFavourite=true
here the durationExact ,isFavourite is optional strings to send and can be used and req.query.durationExact and req.query.isFavourite at server side.
3.GET Sending arrays
{{url}}admin/recordings/sessions/?os["Windows","Linux","Macintosh"]
and you can access those array values at server side like this
let osValues = JSON.parse(req.query.os);
if(osValues.length > 0)
{
for (let i=0; i<osValues.length; i++)
{
console.log(osValues[i])
//do whatever you want to do here
}
}
Just in case somebody ist still coming along this question:
There is a body query object in any request. You do not need to parse it yourself.
E.g. if you want to send an accessToken from a client with GET, you could do it like this:
const request = require('superagent');
request.get(`http://localhost:3000/download?accessToken=${accessToken}`).end((err, res) => {
if (err) throw new Error(err);
console.log(res);
});
The server request object then looks like {request: { ... query: { accessToken: abcfed } ... } }
You know, I have a not so standard way around this. I typically use nextjs. I like to make things restful if at all possible. If I need to make a get request I instead use post and in the body I add a submethod parameter which is GET. At which point my server side handles it. I know it's still a post method technically but this makes the intention clear and I don't need to add any query parameters. Then the get method handles a get request using the data provided in the post method. Hopefully this helps. It's a bit of a side step around proper protocol but it does mean there's no crazy work around and the code on the server side can handle it without any problems. The first thing present in the server side is if(subMethod === "GET"){|DO WHATEVER YOU NEED|}

ClientLogin from Google API doesn't works with AJAX

I'm trying to login to a Google Account for request Picassa Web photos with AJAX. That's the code:
xmlhttp=new XMLHttpRequest();
xmlhttp.open("POST","https://www.google.com/accounts/Login",true);
xmlhttp.send("accountType=HOSTED_OR_GOOGLE&Email=...&Passwd=...&service=lh2&source=prova");
document.getElementById('prova').innerHTML=xmlhttp.responseText;
With this firebug shows a 200 OK status in the Net tab but an unexplained error in the Console. Of course nothing appears in the div called "prova" since answer is empty.
I also try to add this header:
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
But then firebug shows a 400 Bad Request in the Net tab. Can you help me? Thank you.
You should be able to view the ajax reponse in firebug and see what is gtting posted back to you - you can get a 200 error but still get an error in the post back. Don't you need to do something with an AuthToken too?
Solved! Firefox and new browsers don't let make AJAX call to third-party applications for security reasons. All is explained here: http://www.xml.com/pub/a/2005/11/09/fixing-ajax-xmlhttprequest-considered-harmful.html
Wasn't sure if we got the authToken or not...
Here's how I've been making xDomain Posts:
It requires having a little library (tiny) called flyJSONP, which uses YQL (Yahoo! Query Language) as a JSONP hack. Works great, but cannot post/get headers. After, I send data to php which then makes a cross-domain post with necessary header.
FlyJSONP also works with get... FlyJSONP.get({...
FlyJSONP.post({
url: "https://www.google.com/accounts/ClientLogin",
parameters: {
name: "value"
},
success: function(data) {
console.log("the response is: " + data);
},
error: function(errorMsg) {
console.log(errorMsg);
},
complete: function(data){
console.log("...completed post!");
}
});

Categories

Resources