window.fetch .then(), not waiting - javascript

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.

Related

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

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.

get JSON from a Promise

I am using mocha to test a promise that is written in a separate javascript file. I am trying to send data to the promise with a POST request, although I'm not sure what the url should be. Here's what I have so far, using request-promise:
var rp = require('request-promise');
var options = {
method: 'POST',
url: '/algorithm.js',
body: data,
json: true // Automatically stringifies the body to JSON
};
rp(options)
.then(function(body){
count++;
done();
});
The error states that I have an invalid url, although I'm not sure how else to POST to promise inside of a javascript file.
I am trying to send data to the promise with a POST request
You can't do that, at least not directly.
POST requests are for sending data to HTTP servers.
Promises are a JavaScript object for handling asynchronous operations.
These are different things.
algorithm.js needs to either contain code that you can call directly, in which case you should require that code and then call the function.
var algorithm = require("algorithm");
if (algorithm.something()) {
count++;
}
done();
… or it should be server side JavaScript that you need to run an HTTP server for. Once you run the HTTP server, you'll be able to use code like what you wrote in the question, but you'll need to provide an absolute URL since you need to say you are using HTTP and localhost and so on.
var options = {
method: 'POST',
url: 'http://localhost:7878/route/to/algorithm',
body: data,
json: true // Automatically stringifies the body to JSON
};

AngularJS - Stuck Handling response after $resource.save (expecting json)

Hello first of all thanks for your support,
I getting started with angular and I am trying to use conmsume data from an API for my app. I am having a few problems with this.
First of all CORS:
To run local http server I am using the one that comes with node.js (using http-server command).
I am using http://www.mocky.io/ to test the app. I've generated differents (with headers I've found around the net that are supposed to fix it) response there to try to fix CORS (always getting preflight error) but nothing seems to work.
I have added this to my save method (inside a factory):
save: {
method: 'POST',
headers: {
'Access-Control-Allow-Origin': '*'
}
}
If I use a Chrome extension called CORS I can bypass that and receive response but then I am not able to manage the promise and get the data inside the response. I would like to be able to show the response's json on the view.
$scope.submitForm = function() {
var promise = null;
promise = CheckFactory.save($scope.partner).$promise;
$scope.result = promise.data;
}
This functions sends the data from the form to the factory and perform the request but then I am lost and do not know how to manage the data I need from the response.
Thanks in advance :)
Basically you need to put .then function over your save method call promise. So that will call .then function's once data save request gets completed.
$scope.submitForm = function() {
CheckFactory.save($scope.partner).$promise
//it will called success callback when save promise resolved.
.then(function(data){ //success
$scope.result = data;
}, function(error){ //error
});
}

Using Fetch API to Access JSON

I am trying to use fetch api to bring back some data, however am unable to map it to the console once I have retrieved it.
fetch('http://jsonplaceholder.typicode.com/users', {
method: 'GET'
}).then(function(response) {
console.log(response)
response.forEach(i => console.log(i.name));
}).catch(function(err) {
console.log(`Error: ${err}` )
});
The error i get is
response.map is not a function
so I tried to parse the response,(ie var data=JSON.parse) which did not work, with the error
SyntaxError: Unexpected token o in JSON at position 1"
Interestingly, when doing the same thing with a XMLHttp request, I was required to parse it, so I would also be interested to know why the difference between these two methods of retrieving the data.
If anyone could point me in the right direction, I would be really grateful.
The Fetch API returns a response stream in the promise. The response stream is not JSON, so trying to call JSON.parse on it will fail. To correctly parse a JSON response, you'll need to use the response.json function. This returns a promise so you can continue the chain.
fetch('http://jsonplaceholder.typicode.com/users', {
method: 'GET'
})
.then(function(response) { return response.json(); })
.then(function(json) {
// use the json
});
Understanding promises is key to using the fetch API.
At the time you're trying to parse your response and loop through it, the response is actually just a promise. In order to utilize the contents of the actual response from the request, you'll have to do some promise chaining.
fetch('http://jsonplaceholder.typicode.com/users').then(function(response) {
// response.json() returns a promise, use the same .then syntax to work with the results
response.json().then(function(users){
// users is now our actual variable parsed from the json, so we can use it
users.forEach(function(user){
console.log(user.name)
});
});
}).catch(err => console.error(err));
It appears that you might be accessing the json incorrectly. You could try calling response.json() instead.
fetch('http://jsonplaceholder.typicode.com/users', {
method: 'GET'
}).then((response) => {
response.json().then((jsonResponse) => {
console.log(jsonResponse)
})
// assuming your json object is wrapped in an array
response.json().then(i => i.forEach(i => console.log(i.name)))
}).catch((err) => {
console.log(`Error: ${err}` )
});
This example is structured to match your example, but ideally, you would return response.json() on that first .then block and proceed on the next block. Here is a similar example that proceeds on the next block.
In your particular case, you can view the Fetch API as a json aware wrapper for "XMLHttpRequest"s. Main differences being that the Fetch API is simpler, functional-like, and has convenience methods. David Walsh does a reasonable comparison in his blog post, which I recommend you take a look at. Plain "XMLHttpRequest"s just pass you whatever string was sent back from the server, it has no idea it could be JSON, and thus leaves it to the user to parse the response whatever way they see fit.

IE8 changing GET request to POST: Angular $http

I am making call to a REST service from my AngularJS app using $http. The issue is whenever I make a GET request from IE8, it gets converted to POST request. Calls with other http methods (POST,PUT) work fine. This happens only with IE8.
Here is my code
```
var request = {method: method, url: url, data: payload};
var promise = $http(request) .then(function (response) {
return response;
});
```
Can someone please help. I have tried sending different types off data payload : null,undefined,empty object, some object. But nothing worked.
I think I have found the solution. We need to send empty string as payload. Or, use $http.get

Categories

Resources