简体   繁体   中英

js function calling an api doesn't respond with expected values

I am trying to collect all the market pairs from a crypto exchange using its API, but I'm not sure how to select the proper line in the JSON object as it does not seem to work.

the api : https://ftx.com/api/markets

my code : requests.js

import axios from 'axios';
import parsers from './parsers';


async function ftxMarkets() {
    const ftxResponse = await axios.get('https://ftx.com/api/markets');
    return parsers.ftxMarkets(ftxResponse.data);
}

parsers.js

function ftxMarkets(data) {
    const [ftxMarketPairs] = data;
    let ftxPairs = data.map(d => d.name );
    console.log(ftxPairs);

};

I'm not sure about d.name in the parsers.js file, but I tried with another exchange with the same code, changing just that part and it worked, so I guess that's where the problem comes from, although can't be sure and I don't know by what to replace it.

Thanks

I ran the api call and after looking at the response I see a result key with the list of all crypto data. So I am guessing it'll work if you call the parser with the result object like this

    return parsers.ftxMarkets(ftxResponse.result);
    // try parsers.ftxMarkets(ftxResponse.data.result) if the above one doesnt work

and then in the parser it should work normally

function ftxMarkets(data) {
    let ftxPairs = data.map(d => d.name );
    console.log(ftxPairs);
}; 

Update:

Since fxtResponse.data.result works. Your issue should be a CORS issue and to fix that there are two options.

  1. CORS plugin in web browser(not recommended in production)
  2. Proxy it through a server. By requesting the resource through a proxy - The simplest way, what you can do is, write a small node server (or if you already have a back-end associate it with your front-end you can use it) which does the request for the 3rd party API and sends back the response. And in that server response now you can allow cross-origin header.

For 2 If you already have a nodeJs server. You can use CORs Npm package and call the third party api from the server and serve the request to the front end with CORS enabled.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM