How to access request body in "onResourceRequested" callback in PhantomJS? - javascript

I would like to access the request body of HTTP POST requests in the callback registered with onResourceRequested (I didn't find it in the documentation).
I would like to do something like this:
page.onResourceRequested = function(requestData, networkRequest) {
var body = networkRequest.body // how to do that ?
console.log(body)
}
How can I access the body of the request in the onResourceRequested callback ?

The request body of POST requests are stored in the postData attribute of requestData object. You can retrieve it like so:
page.onResourceRequested = function(requestData, networkRequest) {
var body = networkRequest.postData
console.log(body)
}
To note, there doesn't seem to currently be a way to retrieve the request body for any other request methods such as PUT or PATCH.

Related

How can I view the body data of an HTTP request in a Firebase Functions JS?

"I'm trying to view the body data in a Firebase Functions POST request, but the console always returns "undefined" in the Firebase function logs!
Question: How can I view the body data in a Firebase function to use it?
Request :
Here My Code :
exports.test = functions.https.onRequest(async (req, res) => {
const id = req.body.id
});
I allready used but not working :
req.on('data', (chunk) => {
// The chunk is a Buffer object containing a chunk of the request body data
body += chunk;
}).on('end', () => {
// The request body data has been fully received, and the `body` variable contains the complete request body
});
i should to get id from body.id
As per this thread’s answer you should use Content-Type and make it to "application/json"
as only then your body will be accessible like as shown in here
Also you can check out Read values from the request which explains the need of application/json on Content Type.
If you check the firebase functions logs you can see there is no incoming body received from the request and because of that your body content’s are undefined.
There is also a possibility that the req.body property in a Firebase Functions is not properly formatted or if it is not properly parsed by the Function, so you can force it to parse using JSON.parse(req.body); to parse the request body.
So the updated code will something look like:
exports.test = functions.https.onRequest(async (req, res) => {
const body = JSON.parse(req.body);
const id = body.id;
// ...
});
OR
You can use the body parser middleware and force parse the body as JSON as shown in this answer
req.body can be used if the request body type is application/json or application/x-www-form-urlencoded otherwise use req.rawBody

Service worker fetch event for POST request get body

How can I capture the body of POST request in a Service Worker. I am sending authentication parameters in the POST request, so I want to intercept the fetch request in service worker and show results from IndexDB.
Following is the code from my service worker
self.addEventListener("fetch", event => {
let cloned = event.request.clone();
console.log(cloned.json()); //<<- This line returns error : TypeError: Failed to execute 'json' on 'Request': body stream is locked
let response = new Promise((resolve)=>{
let key='mykey'; //Genereate from body, so read body
let stored = localforage.getItem(key);
if(stored){
resolve(stored);
}else{
resolve(fetch(cloned).then(res => res.json()).then(res=>{
localforage.setItem(key,res);
}));
}
})
event.respondWith(response);
})
p.s : please ignore syntax errors if any.
Since request body is ReadableStream, for the reasons #Mr.Vibe mentions in the above comment it cannot be accesed through event.request.body, One way to access the body is by using await event.request.json(), However one should notice that once the request body is read it cannot be reused as body of a request as it throws an error like This ReadableStream is disturbed (has already been read from), and cannot be used as a body. So its better we clone the request and then access its body as in await event.request.clone().json(), So that later on we could use the original request unharmed.
self.addEventListener("fetch", async (event) => {
let clonedBody = await event.request.clone().json();
...
})

AJAX GET request not sending data to Django

I am trying to send data in localStorage via an AJAX GET request to Django, but the Django server never receives it. I am confident that I have data in localStorage("preselection") as console.log shows it. Here is my JavaScript snippet which is inside index.html (am a beginner, so apologies if this is basic and I'm avoiding jQuery for now):
var preselection = localStorage.getItem("preselection");
function previous_selection () {
if (localStorage.getItem("preselection") != null) {
console.log("PRESELECTION IS: ", preselection);
const data = new FormData();
data.append("preselection", preselection);
const request = new XMLHttpRequest();
request.open('GET', '/');
request.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
request.send(data);
request.onload = () => {
var url = '/prebasket';
window.location.href = url;
};
return false;
}
}
previous_selection();
Below is my view in views.py. I tried request.GET.dict(), request.GET.get(), request.GET.copy(), etc. and my data comes as JSON in case it matters, but Django just gets an empty {} or Null for q_preselection:
#login_required
def index(request):
q_preselection = request.GET.dict()
print(q_preselection) # comes back empty
context = {
#irrelevant
}
return render(request, "pizza/index.html", context)
XMLHttpRequest send() does not pass the body data for GET
send() accepts an optional parameter which lets you specify the
request's body; this is primarily used for requests such as PUT. If
the request method is GET or HEAD, the body parameter is ignored and
the request body is set to null.
Use POST instead, you almost never want to have GET request with BODY ( parameters should be passed through URL for GET)

Dojo rpc.JsonService - set custom header

Dojo v1.6.0.
Is there any way to set custom header (spring csrf protection in my case) to every call for all instances of dojo.rpc.JsonService()?
Or at least to every call for specific instances of dojo.rpc.JsonService()?
Problem is in back-end Spring 4 csrf protection which filters everything without specific header in request and returns HTTP 403 Forbidden status.
For now my code looks like:
...
dojo.require("dojo.rpc.RpcService");
dojo.require("dojo.rpc.JsonService");
var myService = new dojo.rpc.JsonService("someMyService");
var result = myService.myRemoteMethod(param1, param2, ... );
...
For example for jQuery code which handles every ajax request and set header to it looks like:
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
$(document).ajaxSend(function (e, xhr, options) {
xhr.setRequestHeader(header, token);
});
It would be perfect to make something like that for dojo.
I haven't found any solution for dojo 1.6, but found that I can fix this problem with handling every ajax request with pure javascript as explained here
So my final solution is:
(function(send) {
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
XMLHttpRequest.prototype.send = function(data) {
if (isNotBlank(token) && isNotBlank(header)) {
this.setRequestHeader(header, token);
}
send.call(this, data);
};
})(XMLHttpRequest.prototype.send);

How to pass cookie as header in angularjs to a remote application that uses drupal [403 Forbidden]

Good day, I am trying to make a $http get request to a remote application that uses drupal in agular.js. Everytime I make a get request i get a 403 response saying [annonymus user]. I am able to make a put request and get a response with a token, session_name, and session_id. My problem is I am not sure how to pass the cookie as part of the request headers. ** **I tried passing cookies as the headers and I still get a 403 response. Any advice will help. I even tried to use $cookie.put('KEY,cookie) to save the cookie but still I get the same response.
var headers = {'Content-Type':'application/json','Cookie':xxxxxx=tokexxxx};
$http.get(url,headers).success(function(data){
// response of the results
console.log('this is the repsonse that come from the get request', response);
}).error(function(err){// 403 error});
My LogIn service looks like this
angular.module('app.services', []).service('LoginService', function($rootScope,$q,$http,$cookies) {
// this is the function that is called when ther user logins
var service = {};
// get cridentials of the user
service.LogIn = function(username,password,callback){
var loginStatus = [];
var BASEURL= http://xxxxxx.com';
var parameters ={username: username,password: password};
var headers = {'Content-Type':'application/json'}
$http.post(BASEURL,parameters,headers).success(function (response) {
// cookie.put
// console.log('response::', {sessionid,token,session,user_data}
$cookies.put(response.session_name,response.token); //
console.log(response.session_name,response.token);
localStorage.setItem('sessid',response.sessid); // locastorage
localStorage.setItem('token',response.token);
console.log(response);
return callback(response); //call this on the controller
});
}
maybe try instead of "cookie:" put "xsrfCookieName" and provide the cookie name.
it should use the token it has in it.
var headers = {'Content-Type':'application/json','xsrfCookieName':'cookieName'};
hope it helps

Categories