I'm a bit stumped. I've forgotten how to do this. I have a function called ext.get() that takes a parameter of url. It fetches a response from the url. The ext.get() function is meant to return the response as a json. I don't think it is doing that.
ext.get = (url) => {
let myHeaders = new Headers();
let options = {
method: 'GET',
headers: myHeaders,
mode: 'cors'
};
//fetch get
fetch(url, options).then(response => {
console.log(JSON.stringify(response.json()))
return JSON.stringify(response.json())
});
};
If you need the response as JSON - and considering
response.json()
effectively the same asresponse.text().then(txt => JSON.parse(txt))
So, the function in full would be
That way you aren't essentially doing
JSON.stringify(JSON.parse(json))
... which is justjson
However, I suspect you want a plain ol' javascript object
You would then use this as:
You are using
fetch
, which is an asynchronous API. This means that your function must also be asynchronous -- i.e. it must return aPromise
. (You could do this with a callback, but this is 2017...)You can't return JSON from the function because the function will return before the response from the server is available. You must return a Promise and deal with it using
then
(orawait
) in your calling code.The simplest and best way to do this here is simply to return the result of the
fetch
call once it has been transformed. You don't want to parse the JSON but to return it as a string. This requires theresponse.text()
call:And your calling code:
or with
await
: