简体   繁体   English

调用 api 的 js 函数没有以预期值响应

[英]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.我正在尝试使用其 API 从加密货币交易所收集所有市场对,但我不确定如何在 JSON 对象中选择正确的行,因为它似乎不起作用。

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

my code : requests.js我的代码: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解析器.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.我不确定 parsers.js 文件中的d.name ,但我尝试使用相同的代码进行另一个交换,只更改那部分并且它起作用了,所以我想这就是问题的来源,虽然不可能当然,我不知道用什么来代替它。

Thanks谢谢

I ran the api call and after looking at the response I see a result key with the list of all crypto data.我运行了 api 调用,在查看响应后,我看到了一个包含所有加密数据列表的结果键。 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.由于 fxtResponse.data.result 有效。 Your issue should be a CORS issue and to fix that there are two options.您的问题应该是 CORS 问题,有两个选项可以解决。

  1. CORS plugin in web browser(not recommended in production) Web 浏览器中的 CORS 插件(不推荐在生产中使用)
  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.通过代理请求资源 - 最简单的方法,你可以做的是,编写一个小型节点服务器(或者如果你已经有一个后端将它与你的前端关联,你可以使用它)它会请求3rd 方 API 并发回响应。 And in that server response now you can allow cross-origin header.现在在该服务器响应中,您可以允许跨域标头。

For 2 If you already have a nodeJs server.对于 2 如果您已经有一个 nodeJs 服务器。 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.您可以使用 CORs Npm 包并从服务器调用第三方 api,并将请求提供给启用 CORS 的前端。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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