I've had a really bad time looking for a solution for this. The only thing that I was able to make for for getting the listening key, was adding this extension to my browser https://chrome.google.com/webstore/detail/allow-cors-access-control/lhobafahddgcelffkeicbaginigeejlf/related?hl=es
I came across some other solutions, like some extra dependencies (axios, for example) or running a proxy server (light-server,or lite-server, or some nodejs-proxy-server), but I was not able to make those work in time really.
For what I was able to see, this CORS policy is a big issue for developers. https://www.youtube.com/results?search_query=cors+javascript+fetch
With that extension I was able to get some information about the Request and Response given to/from the server using DevTools from Chrome. Do you think it may be possible to get some information from those headers I can use in my raw code? So I can get rid of that extension. I tried to use some of the key-value pairs I considered to be part of the solution, even all of them at once, but the error still came up.
Here's an image of the headers from the DevTools:
This code is enough in app.js
for getting the listenKey, with the extension enabled:
/ >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> User
async function getListenKey() {
// const apiKey = myKeys.BINANCE_APIKEY;
// const apiKey = myKeys.TESTNET_APIKEY;
const apiKey = 'you_tesnet_api_key_goes_here'; // Testnet
// const url = 'https://api.binance.com/api/v3/userDataStream';
const url = 'https://testnet.binance.vision/api/v3/userDataStream';
let httpHeaders = {
'Content-Type': 'application/json',
'X-MBX-APIKEY': apiKey
}
let myHeaders = new Headers(httpHeaders);
var requestOptions = {
method: 'POST',
headers: myHeaders,
};
const listenKey = await getJson(url, requestOptions);
console.log(listenKey);
}
getListenKey();
Let me know if that's good code or not, please.
And this is the code for the getJson()
, in src/lib/utilities.mjs
:
// 1
export async function getJson(url = null, requestOptions = null) {
console.log('gJ');
console.log(url);
console.log(requestOptions);
return fetch(url, requestOptions)
.then((response) => {
if (!response.ok) {
throw Error(response.statusText);
} else {
return response.json();
}
})
.catch(function (error) {
console.log(error);
});
}
By the way, these are the CORS extension settings:
And here's the new link to the project repo. I moved it to a private one: https://github.com/carloswm85/binance-api-vanillajs/invitations
The Whitelisted localhost ip. SHould that be there? It is for if disabling CORS on that ip. The link about does not work.