wix-fetch TypeError: Failed to fetch

Hi All,
I’m trying to use a couple of public API’s to get currency rate. One is from OANDA and the other is from the Central Bank of Argentina.

Neither one fetch ok, giving the message TypeError: Failed to fetch when in debug mode.

The page for testing purpose is https://www.propietariovende.online/estamos-trabajando

The error arises when you enter a number value in #imput1 field.

Both codes are as follow:

OANDA:

export function input1_changeOANDA(event) {
//OANDA API:
let the_appi = “https://www1.oanda.com/rates/api/v2/rates/spot.json
let api_key = “kH7ccQB4L5rStAJu0mIGEpQh”;
let myInit = {
“meta”: {
“effective_params”: {
“data_set”: “OANDA”,
“base_currencies”: [“USD”],
“quote_currencies”: [“ARS”],
“interbank”: “5.25%”
},
“endpoint”: “spot”,
“request_time”: “2019-12-26T09:33:04+00:00”,
“skipped_currency_pairs”:
}
};
fetch(the_appi, myInit)
.then((httpResponse) => {
if (httpResponse.ok) {
return httpResponse.json();
} else {
return Promise.reject(“Promesa rechazada”);
}
})
.then(json => $w(‘#text39’).text = json.v)
. catch (err => console.log("Ocurrió un error con la petición: " + err));
}

BCRA:

export function input1_change(event) {
//basado en https://github.com/fedemoglia/variables-economicas-API-datos/blob/master/DolarApiBCRA.gs
let the_appi = “https://api.estadisticasbcra.com/usd_of_minorista
let accessToken = “eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2MDg3NTk3MjgsInR5cGUiOiJleHRlcm5hbCIsInVzZXIiOiJhbGVqYW5kcm8uc2l0b0BnbWFpbC5jb20ifQ.uJb6gPlOxv8gEgHmJJFfsBgaxsxHkyReZeLX3NkNoMWovvO5Oo_M8rA2k2-nvCaXaM3nqYv-sQU3Ahk2QvRQYQ”;
console.log(httpGet(the_appi, accessToken));
// return httpGet(the_appi, accessToken);
function httpGet(url, key) {
const headers = { ‘Authorization’: ‘BEARER ’ + key };
var options = {
‘method’: “GET”,
‘headers’: headers
}
fetch(url, options)
.then((httpResponse) => {
if (httpResponse.ok) {
return httpResponse.json()
} else {
return Promise.reject(“Promesa rechazada”)
}
})
.then(json => { $w(’#text39’).text = $w(‘#text39’).text = json.v;
console.log(json.v) })
. catch (err => console.log("Ocurrió un error con la petición: " + err));
return “Resultado de la función httpGet”
}
}

No problems with other functions that use fetch in that page.

Could someone help me with this issue?

Thanks

The error arises when you enter a number value in #imput1 field - #input1 and not #imput1

Also, note that this is sometimes simply caused by third party extensions (adblocking, popup blockers, tracking etc) on your browser blocking something on your page.

I had to turn off my third party extensions so that your dropdown lists would show, without turning them off there was no way I would have been able to have access to a choice from any of your three dropdown list.

Also, when when I input a number in the user input box underneath your dropdowns, it does not change automatically with the number changing from US Dollars to Argentine peso.

Which I assume is happening to you as well and the correct value is not being returned to you with the onChange event.

So check that you are using the onChange event correctly.
https://www.wix.com/corvid/reference/$w.ValueMixin.html#onChange
onChange( )
Adds an event handler that runs when an input element’s value is changed.
Description
An element receives a change event when a user changes the value in an input element.
A change event is not triggered when you change an element’s value using the element’s value property.

Finally, check the errors that I get when testing the website page.

  • Unchecked runtime.lastError: The message port closed before a response was received.

  • Access to fetch at ‘https://api.estadisticasbcra.com/usd_of_minorista’ from origin ‘https://www.propietariovende.online’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: The ‘Access-Control-Allow-Origin’ header has a value ‘https://estadisticasbcra.com’ that is not equal to the supplied origin. Have the server send the header with a valid value, or, if an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.

  • Access to fetch at ‘https://api.estadisticasbcra.com/usd_of_minorista’ from origin ‘https://www.propietariovende.online’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: The ‘Access-Control-Allow-Origin’ header has a value ‘https://estadisticasbcra.com’ that is not equal to the supplied origin. Have the server send the header with a valid value, or, if an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.

So it seems that you need to check your Wix Fetch requests and make sure that they are correct.

https://www.wix.com/corvid/reference/wix-fetch.html
https://support.wix.com/en/article/corvid-accessing-third-party-services-with-the-fetch-api

http://developer.oanda.com/exchange-rates-api/
http://developer.oanda.com/exchange-rates-api/v2/authentication/

https://estadisticasbcra.com/api/documentation

Hi GOS,
thank you for your response.

I simplyfied the test page for clarification. Also I made changes to the function input1_changeOANDA based on documentation you sugested.

Now the problem is that fetch always derive in Promise.reject.

I’ve hardcoded a couple of values in input1_changeOANDA based on the execution of OANDA Api in an internet explorer.

This URL functions ok:

https://www1.oanda.com/rates/api/v2/rates/spot.json?api_key=kH7ccQB4L5rStAJu0mIGEpQh&base=USD&quote=ARS&interbank=5.25

But not in Wix code:

export function input1_changeOANDA(event) {
//OANDA API:
let the_appi = “https://www1.oanda.com/rates/api/v2/rates/spot.json
let api_key = “kH7ccQB4L5rStAJu0mIGEpQh”;
let myInit = {
“meta”: {
“effective_params”: {
“data_set”: “OANDA”,
“base_currencies”: [“USD”],
“quote_currencies”: [“ARS”],
“interbank”: “5.25%”
},
“endpoint”: “spot”,
“request_time”: “2019-12-26T09:33:04+00:00”,
“skipped_currency_pairs”:
}
};
fetch(the_appi, myInit)
.then((httpResponse) => {
if (httpResponse.ok) {
return httpResponse.json();
} else {
return Promise.reject(“Fetch did not succeed, promise rejected.” );
}
})
.then(json => $w(‘#text39’).text = String(Number(json.quotes.ask) * Number($w(‘#input1’).value) ))
. catch (err => console.log("Error when trying to fetch: " + err));
}

I also tried to change the rate function with one of the examples in documentation you provided:

export function buttonFetchRate_click(event) {
let url = “https://api.exchangeratesapi.io/latest?base=USD”;
let symbol = ‘ARS’;
let fullUrl = url + “&symbols=” + symbol;

fetch(fullUrl, {method: ‘get’})
.then(response => response.json())
.then(json => $w(“#text39”).text = json.rates[symbol].toString());
}

But this API dos not works for Argentinian pesos (ARS).

Could you please give another look to my function input1_changeOANDA?.

Following is an image of the test:

Thank you in advance.
A.S.

Ale, just as GOS said, you will have to inspect your JSON-request first. Easiest way to figure it out is using Postman. Have you tried that yet?

Hi Giri,
I’m not a developer and I don’t understand what is Postman. Also I don’t understand what you means with “inspect your JSON-request first”.

As I said the explorer request, in Chrome for example, works fine. Have you tried it?:

https://www1.oanda.com/rates/api/v2/rates/spot.json?api_key=kH7ccQB4L5rStAJu0mIGEpQh&base=USD&quote=ARS&interbank=5.25

In the following sentences I asume that inspecting the request is made by the “if” clause. Or not?

fetch(the_appi, myInit)
.then((httpResponse) => {
if (httpResponse.ok) {
return httpResponse.json();
}
else {return Promise.reject(“Fetch did not succeed, promise rejected.” );
}

Have you tried yourself using OANDA’s apis?. If so, perhaps you could give me a direct response.

Thanks,
Ale

Hi all,
dismiss this thread as I just solved my problem.

Thanks.

Great. Could you post your solution so others could learn from it?

Hi everybody,
I found another simpler API to use in currencydatafeed.com.

I create a function named dolarCDF() and invoke it when my dynamic page has been loaded. In this page I have a value in USD currency and get the conversion rate USD/ARS to charge a text field with the value in ARS.

Main things are as follows:

/**

function httpGet(url, key) {
const headers = { ‘Authorization’: ‘BEARER ’ + key };
var options = {
‘method’: ‘get’,
‘headers’: headers
}
fetch(url, options)
.then((httpResponse) => {
if (httpResponse.ok) {
return httpResponse.json()
} else {
return Promise.reject(“Promesa rechazada”)
}
})
.then(json => {
var l_rate = json.currency[0].value * 1.055;
console.log(l_rate);
$w(’#textExchangeRate’).text = String(l_rate);
console.log(‘textExchangeRate=’ + $w(‘#textExchangeRate’).text);
$w(‘#textARSformatted’).text = "AR$ " + number_format( l_rate * Number($w(‘#textUSDnumber’).text), 0);
$w(‘#textRateString’).text = "(tipo de cambio del día: " + number_format($w(‘#textExchangeRate’).text, 4) + “)”;
return l_rate;
})
. catch (err => console.log("Ocurrió un error con la petición: " + err));
}

Hope this help someone else.

Regards,
Ale

Thank you for posting your solution.
Y flaco, que no ovides cambiar este:

var l_rate = json.currency[0].value * 1.055;

en este:

var l_rate = json.currency[0].value * 1.055 * 1.3;   // al dólar turista

Jajajajajajajjaj!!