Fetching html content from URL [Javascript in Script Labs (Office)] - javascript

Simply put, I am trying to fetch the html content from url "http://anovamoeda.oinvestidordesucesso.com/IS/nmREPORT.asp?NM=2" from inside the Script Labs environment, when running through Excel. A simple fetch(url) returns this enigmatic error message:
TypeError {}
description: "Failed to fetch"
message: "Failed to fetch"
number: -2147418113
▶__proto__: TypeError
▶constructor: function TypeError()
message: ""
name: "TypeError"
▶toString: function toString()
▶__proto__: Error
I could figure out that this is a network error (the promise returns rejected), which seems weird because I did also try to fetch JSON from an API and it worked fine (for instance, https://api.binance.com/sapi/v1/system/status for those willing to try). First I thought it might be due to my url having html content, not JSON, but it is not like it cannot parse the information, it doesn't even get information to try. I tried to add a parameter to the fetch call passing {headers: {'Content-Type': 'text/html'}}, but that didn't work. (Also, I'm a noob in JS.)
But I could fetch the information from inside Google Scripts, using their own UrlFetchApp API with a simple call to that fetch method.
Happy with any help as I could not find any.

You don't show enough code so I am not sure what you are doing. That URL does not return json: it is an html document. if you want the text of the html document try this:
var response = await fetch("http://anovamoeda.oinvestidordesucesso.com/IS/nmREPORT.asp?NM=2");
if (response.ok) {
var content = await response.text();
// parse the content
console.log(content);
}
else {
// handle error response
}

I believe I figured out what is happening. According to this thread buried in the depths of GitHub, Script Lab supports only https. Sad world this we live in.

Related

Fetch GET request unhandled rejection

I'm doing a basic request to a backend in JS (only to check a user instance exists and will return a bool (true/false) to prevent returning full user data until needed)
From what I have been told by peers it's ill-advised to be passing sensitive data (in this case people's emails) via paths and should be via the body (I haven't looked into why) Anyway, so the way I configured it was to be contained within the body like this:
GET http://localhost:8080/User/check
Content-Type: application/json
{
"email" : "B.Nye#ABC.uk"
}
However when doing this call in JS:
if (isAuthenticated){
console.log("test -----------")
console.log(user.email)
fetch("http://###.###.###.###:8080/User/check", {
method: "GET",
headers:{"Content-Type":"application/json"},
body: JSON.stringify( {
email: "B.Nye#ABC.uk"
})
}).then((result)=> {
if (result.ok){
console.log("sucess")
}
else{
console.log("fail")
}})}
I get this error:
Unhandled Rejection (TypeError): Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot have body.
Is there a way to bypass this or am I restricted to using either a POST method and reworking my backend method or containing the users email inside of the path?
Firstly if you want to use body, you should use POST method. This is why the Fetch API keeps sending errors to you.
The second question is, why do we not use GET method while we are sending sensitive datas like emails, passwords etc. The answer is, entire URL is cached user's browser history and it may expose user's sensitive data. And it will be much more secure if you use POST method because it prevents data leakage via the query string (you are sending data in the body).

Console log raw data of a failed Axios get request

I would like to make an Axios get request to a private server running Flask.
In case there is an internal error in the back-end it returns an response object and an error code.:
response_object = {
"Success": False,
'error': err.message
}
return response_object, 400
The served response_object should be accessible the front-end (React.js).
axios
.get(`http://127.0.0.1:5000/data`, {
data: null,
headers: { "Content-Type": "application/json" }
})
.then(response => {
console.log(response);
})
.catch(function(error) {
console.log(error.toJSON());
});
I would expect the error to include the response object. If the URL is accessed manually in the browser the error data is visible. If there is no error in the back-end the get requests works properly.
After googling for some time I found some issues that might relate to the mentioned problem. (That is why empty data is passed in the a get request).
https://github.com/axios/axios/issues/86
https://github.com/axios/axios/issues/86
Please note that I am self taught so I might miss something obvious here. Thank you all and all the best.
I'll copy/paste my comment here so other can easily see the answer for the question
if it's a 400 status code that it's throwing (you can confirm by using the Network tab in your browser), it will fall into the catch block, the only concern is the toJSON() call... just do a simple console.log(error.message) to check if you ever get there...
I leave you a simple example so you see the catch in action
more information:
in Axios, the response text is in response.data
if you are receiving a JSON, the response.data will be automatically parsed
you do not need to pass data: null as that's the default behavior, and it's not used in a GET call (you won't pass a body in a GET call)

Native JS fetch API complete error handling. How?

I've put together the following code from learning about the fetch API. I am trying to replace AJAX and this looks wonderful so far.
Main Question:
According to the Fetch API documentation...
A fetch() promise will reject with a TypeError when a network error is
encountered or CORS is misconfigured on the server side, although this
usually means permission issues or similar — a 404 does not constitute
a network error, for example.
Having the 3 technologies working together...
If I disable the Web Server I get:
NetworkError when attempting to fetch resource.
Wonderful. That works great.
If I disable MySQL I get my custom error from PHP:
MySQL server down?
Wonderful. That works great.
If I disable PHP I get exactly nothing because the only way I can think of to pass through the Web Server request and trigger an error at the PHP level is with a... timeout.
After some research, I don't think there is a timeout option... at least not yet.
How could I implement it in the code below?
// CLICK EVENT
$( "#btn_test" ).on('click', function() {
// Call function
test1();
});
function test1() {
// json() - Returns a promise that resolves with a JSON object.
function json_response(response) {
// Check if response was ok.
if(response.ok) {
return response.json()
}
}
// data - Access JSON data & process it.
function json_response_data(data) {
console.log('json_response_data: ', data);
}
// URL to post request to...
var url = 'data_get_json_select_distinct_client.php';
// Sample serializeArray() from html form data.
// <input type="text" name="CLIENT_ID" value="1000">
var post_data = [{
"name":"CLIENT_ID",
"value":"1000"
}];
// STRINGIFY
post_data = JSON.stringify(post_data);
// FETCH
fetch(url, {
method: 'post',
headers: new Headers({'Content-Type': 'application/json; charset=utf-8'}),
body: post_data
})
// VALID JSON FROM SERVER?
.then(json_response)
// ACCESS JSON DATA.
.then(json_response_data)
// ERROR.
.catch(function(error) {
console.log('Web server down?: ', error.message);
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<button type="button" id="btn_test">FETCH RECORD</button>
Your server should be returning some sort of 5xx error code, should there be a problem server-side. This error is catchable in your JS.

How to get callback error to alert in JavaScript?

I am building app with PhoneGap. It working fine on my PC. But when I installed it as android app it did not work. It fire alert('Oppps...something went wrong').
I have following code...
function getFloors(url, callback){
var data = $.ajax({
type: 'GET',
url: "http://example.com/all_test/get_floors.php"
}).done(callback).error(function(e){
alert('Oppps...something went wrong')
});
return data;
};
Let assume there is no page like http://example.com/all_test/get_floors.php.
Then you can find error in console like GET http://example.com/all_test/get_floorss.php 404 (Not Found).
I need to display that error as alert. I mean I need to print real error instead of alert('Oppps...something went wrong'). So I can find what is issue in mobile.
How should I get that error (what display on the console) for a alert.
Look at this documentation
http://api.jquery.com/jQuery.ajax/#jqXHR
the e on error(function(e) returns a jqXHR object which returns following properties that you can print at your disposal
readyState
responseXML and/or responseText - when the underlying request responded
with xml and/or text, respectively
status
statusText
I think you are trying to find the e.responseText or e.responseXML

window.fetch .then(), not waiting

Using window.fetch() in Firefox and Chrome to get data from a local JSON file, is proving troublesome:
var url = "http://sandbox.ccchapel.com/Thy-Kingdom-Come/data/outreach-spree.json";
var request = new Request(url, {
method: 'get',
mode: 'no-cors'
});
fetch(request).then(function(response) {
console.log(response);
return response.json();
}).then(function(j) {
console.log(j);
});
For whatever reason, the first .then() function is being called prior to the full AJAX response, resulting in promise object (response) being
<state>: "pending"
Which leads to an unwanted output as I'm not getting the data I wanted to get.
I've looked at multiple documents on I can't seem to find anything on my end that I'm doing incorrectly.
Any ideas?
The posted code is fine as it is. Replace the url with
var url =
"data:application/octet-stream;base64,eyJncmVldGluZyI6ICJoZWxsbyBmb2xrcyJ9Cgo=";
({"greeting": "hello folks"}) to see it in action.
What appears to be missing is a .catch clause on the promise chain to report parsing errors in the .json file.
After a bit more Googling, I found this article by Google: https://developers.google.com/web/updates/2015/03/introduction-to-fetch#chaining-promises
Looks like you have to build some extra functions to wait for the status to be resolved. This will then pass the response properly, as you'd expect.

Categories

Resources