How can i check the HTML document GET request status? - javascript

I am doing "window.open(file_url)" to download a file and if a file exists backend returns a Blob which gets downloaded by the browser but if the file doesn't exist then backend returns a JSON error message with request status as 500.
so is there is some way to know that "status" for a page.
I know for AJAX we get the status property but for normal web pages do we have some way to know that status since when the browser makes a request for a page its an HTTP GET and it should have status.

This is a working example code. So, you should use it.
$.get(url, function(data,status, xhr) {
alert(xhr.status);
});

You can check for error as
var test = window.open(file_url)
test.onError = alert('The specified file was not found. Has it been renamed or
removed?');

Related

How to get error HTTP status code in react admin

I am using react-admin framework and I am trying to get error status code (404,500), which I would be saving to some variable for later usage. For example, when I try to create an user that has same e-mail address as already created user, the server wont allow this operation and the request fails with status code 500.
I need that status code to save to variable and work with it later.
Does react-admin offer this?
So far I have tried this simple code in my custom DataProvider, but when logging it to console, it returns undefined.
const status = params.message.status;
I wasn't able to find any other solution that I would fully understand.
Any ideas how to solve this?
Thank you in advance.
Basically this is what are you looking for:
https://developer.mozilla.org/en-US/docs/Web/API/Response/status
First of all, you actually need to request some data from the server in order to get the response.status code.
The most simple example would be this based on the link I listed before:
var myRequest = new Request(options.body); //depends on what do you want to request
fetch(myRequest).then(function (response) { //gets the response from server
console.log(response.status, 'status'); // this returns the status value
});
This should return the response.status code.

How can I GET content of a HTTPS webpage?

I want to get the content of a webpage by running javascript code on NodeJs . I want the content to be exactly the same as what I see in the browser.
This is the URL :
https://www.realtor.ca/Residential/Single-Family/17219235/2103-1185-THE-HIGH-STREET-Coquitlam-British-Columbia-V3B0A9
I use the following code but I get 405 in response.
var fs = require('fs');
var link = 'https://www.realtor.ca/Residential/Single-Family/17219235/2103-1185-THE-HIGH-STREET-Coquitlam-British-Columbia-V3B0A9';
var request = require('request');
request(link, function (error, response, body) {
fs.writeFile("realestatedata.html", body, function(err) {
if(err) {
console.log('error in saving the file');
return console.log(err);
}
console.log("The file was saved!");
});
})
The file which is saved is not related to what I can see in the browser.
I think a real answer will be easier to understand since my comment was truncated.
It seems the method of the request you send is not supported by the server (405 Method Not Allowed - The method specified in the Request-Line is not allowed for the resource identified by the Request-URI. The response MUST include an Allow header containing a list of valid methods for the requested resource.). Do you have more information about the HTTP response.
Have you tried the following code instead of yours ?
request('https://www.realtor.ca/Residential/Single-Family/17219235/2103-1185-THE-HIGH-STREET-Coquitlam-British-Columbia-V3B0A9').pipe(fs.createWriteStream('realestatedata.html'))
You could also have a look at In Node.js / Express, how do I "download" a page and gets its HTML?.
Note that anyway the page will not render the same way when you only open the html since it also requires many other resources (110 requests are done when display the page).
I think the following answer can help you to download the whole page.
https://stackoverflow.com/a/34935427/1630604

Getting response body for AJAX requests with SlimerJS

I'm writing a test using SlimerJS for a website and need to check the response body coming from the server. I'm using the following piece of code to get the response:
page.onResourceReceived = function (response) {
console.log(JSON.stringify(response));
};
I do receive the response but since by default to prevent too much memory usage SlimerJS keeps the response body empty I too receive an empty body, unless I tell it not to keep the body empty for certain formats using something like this:
webpage.captureContent = [ /css/, /image\/.*/ ]
I understand this works well for files with extensions like css,jpg and avi, but what about an AJAX response coming from the server. The response is in JSON format and the response body is left empty.
By looking at the response header you can tell that the response type is in text/html so by using the following code you can get the body.
page.captureContent = [/text/, /html/]

Parse.com getting data from callback URL

I'm currently trying to use an API and for the API, the developer console of that app asks the developer to submit a callback URL. Whenever the user of the app does something, it submits a GET request to the callback URL and I can retrieve data from that request. The current url I am using is https://appId:javascript-key=myJavascriptKey#api.parse.com/1/functions/receiveInfo. How can I handle the data, a.k.a the GET parameters, from the GET request? I found an answer on Parse.com that says how to retrieve data from a POST request, but all it says is that data = request.body. Do I do the same for GET requests and if so what do I do after that? Is request.body a json value?
Parse.Cloud.define("receiveInfo", function(request,response){
var params = request.body;//is this right to get the GET parameters they send? if so what do I do next?
});
The documentation has your solution at: https://parse.com/docs/cloud_code_guide#functions
For GET requests you have to use the request.params object which has all your request parameters for a GET are there. POSTS are sent in the request body, GET in the request parameters.
It looks like you are trying to get the params you can use something similar to:
Parse.Cloud.define("myMethod", function(request, response) {
if(request.params.myparam == "moo") {
response.success("Cow!");
}
else {
response.error("Unknown type of animal");
}
});

How do you properly and reliably load JSON data cross-site?

I'm currently working on a userscript/extension for Chrome and am trying to pull in some JSON data from "some website". This was my approach:
$.get( "http://cloud.hartwig-at.de/~oliver/superuser.json",
function( data ) { console.log( data ); }
);
Of course, that leads to the following error:
XMLHttpRequest cannot load http://cloud.hartwig-at.de/~oliver/superuser.json. Origin http://superuser.com is not allowed by Access-Control-Allow-Origin.
I was able to resolve that after reading Origin 'url' is not allowed by Access-Control-Allow-Origin (among other questions). So, this is the next version:
$.get( "http://cloud.hartwig-at.de/~oliver/superuser.json",
function( data ) { console.log( data ); },
"jsonp"
);
Sadly, that results in another error:
Uncaught SyntaxError: Unexpected token : (superuser.json:2)
There's also a warning telling me "Resource interpreted as Script but transferred with MIME type text/plain:" which already gave me an idea what the trouble could be. (And more details were provided through Chrome says "Resource interpreted as script but transferred with MIME type text/plain.", what gives?)
Apparently, the HTTP server has to send the proper MIME type for my file, which would be application/json.
Okay, So I quickly added the required change to my mime.types and went for another go. But, no dice! The warning went away, the error didn't. I still get Uncaught SyntaxError: Unexpected token :. (I had also previously attempted to utilize the mimeType parameter to fix this, the outcome was the same.)
The MIME type looks fine though:
Now I'm somewhat out of ideas. The content of the .json file validates fine on http://www.jslint.com/
Telling the jQuery's get to do JSONP does not magically make it work. It makes a JSONP request, but the server on the other end needs to support JSONP calls.
The response from the server should look something like
someFunction( { "foo" : "bar" } );
See jQuery's docs on getJSON with JSONP to see how to use the callback
If it is a modern day browser you can use CORS and you have control over the second domain.
Other option is a serverside proxy on your domain that requests data from the other domain. Or you can use a service like Yahoo pipes.
You can't use JSONP on a request unless the server supports it. The way JSONP calls work is that you pass a callback=something parameter along with the request and the server encapsulates the JSON with something() so that it can be loaded by your browser by calling something when the script is accessed.
Another way to get it to work is to configure that server to set the CORS headers correctly, if you own the domain.
If you don't have access to the server, consider using a JSONP proxy, which wraps the first step for you. I've used YQL to do this (see the link), which doesn't require me to set anything up myself. Below is coffeescript code that does that:
uri = "http://cloud.hartwig-at.de/~oliver/superuser.json"
jqxhr = $.getJSON \
"http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22" \
+ encodeURIComponent(uri) + "%22&format=json&callback=?"
jqxhr.success (yql) ->
unless yql.query.results
alert("Failed to get stuff")
return
json = $.parseJSON(yql.query.results.body.p)
# do stuff with json
And in the form of javascript using http://js2coffee.org:
uri = "http://cloud.hartwig-at.de/~oliver/superuser.json";
jqxhr = $.getJSON("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22"
+ encodeURIComponent(uri) + "%22&format=json&callback=?");
jqxhr.success(function(yql) {
var json;
if (!yql.query.results) {
alert("Failed to get stuff");
return;
}
json = $.parseJSON(yql.query.results.body.p);
// do stuff with json
});

Categories