Unable to parse headers from successful HTTP HEAD request in jquery? - javascript

I am using the following code to get file-size of a url, the debugger shows requests to be executed with HTTP STATUS CODE 200 returning all headers including 'Content-Length' however my code outputting NULL values for headers (even after the request succeeded).
function checkURL(url) {
try {
var xhr = $.ajax({
type: "HEAD",
url: url,
async: false,
success: function (data) {
result = data;
}
});
console.log('Size :' + xhr.getResponseHeader('Content-Length'));
} catch (e) {
console.log('XHR Error :' + e);
}
}
EDIT # 1
I tested the below code and it works, however not all headers are being displayed. Once again HTTP DEBUGGER shows the elusive 'Content-Length' header to be present in reply to this XHR.
function checkURL(url) {
try {
var xhr = $.ajax({
type : "HEAD",
url : url,
complete : function (XMLHttpRequest, textStatus) {
console.log(XMLHttpRequest.getAllResponseHeaders());
}
});
} catch (e) {
console.log('Check Size XHR Error :' + e);
}
}

Whats is your type HEAD ?
it must be a xml or json !

Related

jQuery .ajax to Vanilla JavaScript

I am trying to convert an ajax request to vanilla JavaScript
$.ajax({
url: 'http://foo.bar/hi',
type: 'post',
data: {args: params},
success: function(data){
},
});
I have tried the following
var xhr = new XMLHttpRequest();
var data = {args: params};
xhr.open("POST", 'http://foo.bar/hi', true);
xhr.send(data);
I am connecting to an external device with a web based interface and not getting any response on the device. It is as if I never sent a request
Theoretically, the original ajax request will perform the action, however, there is a problem with the jQuery portion of my program so I am trying to convert it to vanilla javascript and bypass the jQuery
Using fetch:
function json(response) {
return response.json();
}
function handleErrors(response) {
if(!response.ok) {
throw new Error("Request failed " + response.statusText);
}
return response;
}
fetch("http://url.com/endpoint", {
method: "POST",
body: {
myKey: "my value",
another: "hihihi"
}
}).then(handleErrors).then(json).then(function(data) {
console.log(JSON.stringify(data));
}).catch(function(err){
console.log("err" + err);
})

DP urlopen in gateway script for datapower

Can anybody please provide me a sample gateway script with dp-url open() contains.
1. dynamic headers
2.https call
3. response type is json
4.ssl client profile
5.form url encoded
6. POST
And how to use a specific value in response.
please help me, this is very much helpful to me,
Thanks in advance,
Manoj.
here is a sample code for url open in Datapower.
var options = {
target: endPoint url,
method: 'post',
timeout: 60,
headers: {
"Authorization": Auth
},
data: json
};
urlOpen.open(options, function(error, response) {
if (error) {
session.reject("Unexpected error in readAsJSON(): " + error);
return;
} else {
response.readAsJSON(function(error, jsonObj) {
if (error) {
session.reject("Unexpected error in readAsJSON(): " + error);
return;
} else {
session.output.write(jsonObj);
}
});
}
});

Regarding the iteration query in node.js with mysql

After the update request is sent, I would like to get a success/fail response.
Regarding the response, I have to receive the one response after all update query is performed.
How to receive the one response?
The following code is my node.js server example.
Thank you!!
$.ajax({
url: "http://127.0.0.1:62590/updatingResourceList",
type: "put",
dataType: "text",
cache: false,
timeout: 30000,
data: JSON.stringify(jsonObject),
contentType: "application/json",
success: function (data) {
alert("Success updating the resource");
}, error: function (xhr, textStatus, errorThrown) {
alert(textStatus + ' : ' + errorThrown);
}
});
=========================================================================
app.put('/updatingResourceList', function (request, response) {
var resultObj = request.body;
var updatedIDList = resultObj['idList'];
// Updating the user request format
var idCounting = 0;
for(var i = 0; i < updatedIDList.length; i++) {
var latest = timestamp();
var resourceName = updatedIDList[i];
var client = dbClient.getDBClient(); // Getting Database information.
client.query('UPDATE testset SET time=? WHERE resourceName=?', [latest, resourceName], function (error, results, fields) {
if (error) { // error
console.log("MySQL : Database resource update error : " + error);
response.status(500).end();
} else { // success
console.log('MySQL : Success updating the resource : ' + resourceName);
response.status(200).end();
}
});
}
});
The problem is that you are sending back a response at each iteration of the loop. If you want a single response, then do it only after the loop. In the loop keep track of the results of the update in an array (key should be the resourceName), and send back the results in one go, perhaps as a json object.
What you need to decide, however, is how to handle if only some of the updates are successful. You either have to return an OK (status code 200), or an internal error at the end.

getting json with fetch and ajax yields different responses

I have been using ajax to get back some json data and recently tried using the fetch implementation.
I am having different responses, my ajax returns a string with all my key/value pairs, while the fetch query is returning response objects which do not at all contain any of my key/value pairs. (I am requesting the exact same resource in both examples and receiving different responses)
Could anyone let me know what Im doing wrong or why this is happening?
ajax request:
$.ajax({
url: "/" + name + ".json",
dataType: "text",
success: function (data) {
console.log(data);
var json = $.parseJSON(data);
var itemArray = [];
$.each(json, function() {
itemArray.push( { value: this.id, label: this.name } );
});
//Populate the List
populateListBox(name, itemArray);
}
});
console log result: (this is the response I want to be getting using the fetch method)
[{"id":1,"name":"two on two","abbreviation":"2v2","inhouse":true,"length":50,"capacity":1,"price":"50.2","salary":"15.22","url":"http://localhost:3000/en/products/1.json"},{"id":2,"name":"threesome Lessons","abbreviation":"3SUM","inhouse":false,"length":50,"capacity":3,"price":"33.33","salary":"11.11","url":"http://localhost:3000/en/products/2.json"},{"id":3,"name":"Prod1","abbreviation":"PRR1","inhouse":true,"length":22,"capacity":2,"price":"20.0","salary":"20.0","url":"http://localhost:3000/en/products/3.json"}]
fetch request:
fetch("/" + name + ".json")
.then(function(response) {
console.log(response);
return response.json()
}).then(function(json) {
var itemArray = populateItemArray(this, json);
populateListBox(name, itemArray);
}).catch(function(ex) {
console.log('parsing failed', ex)
});
console log result: (Response an object full of other objects but seems to be only an html response without any of my requested data)
Response {}
body: (...)
bodyUsed: false
headers: Headers
ok: true
status: 200
statusText: "OK"
type: "basic"
url: "http://localhost:3000/login?locale=en"
proto: Response
I am also receiving an error in the console using the fetch method which states the following: **
SyntaxError: Unexpected token <
**
Hope someone can assist. :)
UPDATE: After closely inspecting my headers in both requests I noticed the following: My AJAX request sends through a CSRF token, as well as a cookie in the header.
All fetch requests are made as anonymous and unauthenticated (by default)
All that was needed was to add an option to the fetch request as follows:
fetch("/" + name + ".json", **{ credentials: 'same-origin' }**)
.then(function(response) {
return response.json()
}).then(function(json) {
var itemArray = populateItemArray(json);
itemArray = sortByLabel(itemArray, 'label');
populateListBox(name, itemArray);
}).catch(function(ex) {
console.log('parsing failed', ex)
});
Problem is solved! Took me long enough - the CSRF token is not needed but the cookie is definitely required as that is what allows the request to be an authenticated one. :)
fetch requires a parameter to make its requests authenticated:
credentials: 'same-origin'
Not sure, maybe change dataType: "text" to "json"?

catch jquery ajax error later

I try to make an http request to a freebox ( I don't know if it's exist outside france )
The freebox don't access the CORS request, but she make what I will.
For example if I make a request for power :
http://hd1.freebox.fr/pub/remote_control?code=5818260&key=power&long=false&repeat=1
The freebox player start, and I have a CORS error:
XMLHttpRequest cannot load http://hd1.freebox.fr/pub/remote_control?code=5818260&key=power&long=false&repeat=1. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
It's okay, but I will check the http header for this request, for example if I will check if my code is good, the freebox return 403 for bad code.
I tried to get the statusCode with Jquery :
xhr = $.ajax({
method: "GET",
url: url,
crossDomain: true,
statusCode: {
500: function () {
alert("Une erreur s'est produite !");
},
403: function(){
alert("aaaaa")
throw new badTelecommandeCode();
},
404: function(){
throw new freeboxNotFound();
},
0: function(){console.log(0)}
},
error: function (err) {
console.log(err);
}
});
All this time, the status code is 0, and "error" don't launch. I have this error in console :
XMLHttpRequest cannot load http://hd1.freebox.fr/pub/remote_control?code=5818260&key=power&long=false&repeat=1. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 403.
You can see the end of this answer
"The response had HTTP status code 403.".
Just before jquery write an error ( in red ):
GET http://hd1.freebox.fr/pub/remote_control?code=5818260&key=power&long=false&repeat=1
I try to catch the error :
try{
xhr = $.ajax({
method: "GET",
url: url,
crossDomain: true,
statusCode: {
500: function () {
alert("Une erreur s'est produite !");
},
403: function(){
alert("aaaaa")
throw new badTelecommandeCode();
},
404: function(){
throw new freeboxNotFound();
}
},
error: function (err) {
console.log(err);
}
});
}
catch(err){
console.log(err);
}
I have try to search, where the error has catch by jquery :
http://code.jquery.com/jquery-2.1.4.js line 8634
Do You find a way for catch the CORS message, and parse it, or catch the jquery message, and why not get the statusCode or any information .
For the little troller, the way "Send a request to freebox developer for accept CORS" is already make, but no answer. I can't pass by a webserver .
My Current challenge is : "I'm a lambda user will see my TV, but my Free Tv Remote don't work, what I can make easily, with my smartphone/PC"
UPDATE1 :
I have make an example :
if it's work good :
xhr = $.ajax({
method: "GET",
url: "http://hd1.freebox.fr/pub/remote_control?code=5818261&key=right&long=false&repeat=1",
crossDomain: true,
statusCode: {
500: function () {
alert("Une erreur s'est produite !");
},
403: function(){
alert("badTelecommandeCode")
},
404: function(){
alert("freeboxNotFound")
}
},
error: function (err) {
// console.log(err);
},
fail:function(jqxhr, textStatus, errorThrown) {
// console.log(errorThrown);
}
});
Good key, good code, my TV make the action, and return a CORS error
I will catch, if the code is bad, or if the key doesn't exist :
xhr = $.ajax({
method: "GET",
url: "http://hd1.freebox.fr/pub/remote_control?code=5818261&key=ping",
crossDomain: true,
statusCode: {
500: function () {
alert("Une erreur s'est produite !");
},
403: function(){
alert("badTelecommandeCode")
},
404: function(){
alert("freeboxNotFound")
}
},
error: function (err) {
// console.log(err);
},
fail:function(jqxhr, textStatus, errorThrown) {
// console.log(errorThrown);
}
});
xhr = $.ajax({
method: "GET",
url: "http://hd1.freebox.fr/pub/remote_control?code=222222&key=ping",
crossDomain: true,
statusCode: {
500: function () {
alert("Une erreur s'est produite !");
},
403: function(){
alert("badTelecommandeCode")
},
404: function(){
alert("freeboxNotFound")
}
},
error: function (err) {
// console.log(err);
},
fail:function(jqxhr, textStatus, errorThrown) {
// console.log(errorThrown);
}
});
I have a CORS, no problem, but how I can catch the text, say the http status .
For information :
freebox.fr is a NAT rules, redirect to my router ( the freebox ), hdX.freebox.fr go to the API for TV player hd number X
Still not certain interpret Question correctly. There does not appear to be a response returned from url . 0 does not appear to be a valid HTTP response code see HTTP status code 0 - what does this mean for fetch, or XMLHttpRequest? . The error logged to console
GET http://hd1.freebox.fr/pub/remote_control?code=5818260&key=power&long=false&repeat=1 net::ERR_CONNECTION_TIMED_OUT
after request below
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://hd1.freebox.fr/pub/remote_control?code=5818260&key=power&long=false&repeat=1", true);
xhr.onload = function() {
console.log(this.status)
}
xhr.onerror = function(e) {
console.log(e, this.status)
}
xhr.send();

Categories