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 as response.text().then(txt => JSON.parse(txt))
return fetch(url, options).then(response => response.text());
So, the function in full would be
ext.get = (url) => {
let myHeaders = new Headers();
let options = {
method: 'GET',
headers: myHeaders,
mode: 'cors'
};
return fetch(url, options).then(response => response.text());
};
That way you aren't essentially doing JSON.stringify(JSON.parse(json))
... which is just json
However, I suspect you want a plain ol' javascript object
ext.get = (url) => {
let myHeaders = new Headers();
let options = {
method: 'GET',
headers: myHeaders,
mode: 'cors'
};
return fetch(url, options).then(response => response.json());
};
You would then use this as:
ext.get('url').then(result => {
// result is the parsed JSON - i.e. a plan ol' javascript object
});
You are using fetch
, which is an asynchronous API. This means that your function must also be asynchronous -- i.e. it must return a Promise
. (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
(or await
) 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 the response.text()
call:
ext.get = (url) => {
let myHeaders = new Headers();
let options = {
method: 'GET',
headers: myHeaders,
mode: 'cors'
};
//fetch get
return fetch(url, options).then(response => response.text());
};
And your calling code:
ext.get('http://example.com').then((response) => {
console.log(response); // or whatever
});
or with await
:
let response = await ext.get("http://example.com");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With