首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >React Native,在源代码中使用RapidAPI

React Native,在源代码中使用RapidAPI
EN

Stack Overflow用户
提问于 2020-11-08 19:01:36
回答 1查看 100关注 0票数 0

我曾经使用以下代码来检索JSON文件,该文件在我的React Naive源代码中包含个人数据:

代码语言:javascript
复制
async componentDidMount() {
try {
    const response = await fetch('mydomain.org/personaldata.json');
    const responseJson = await response.json();
    this.setState({
        isLoading: false,
        dataSource: responseJson,
    });
}
catch (error) {
    console.error(error);
}
}

然后我决定使用RapidAPI使它更安全,但我不知道如何使用它,它给我的白色页面没有数据:这是我修改后的代码:

代码语言:javascript
复制
async componentDidMount() {
try {
    const response = await fetch('coin-flip1.p.rapidapi.com/headstails', {
        "method": "GET",
        "headers": {
          "x-rapidapi-host": "mydomain.org",
          "x-rapidapi-key": 'lkweruytv43578tv3urhgciuyv2b738465873465c87xnb746'
        }
      });
    const responseJson = await response.json();
    this.setState({
        isLoading: false,
        dataSource: responseJson,

    });
}
catch (error) {
    console.error(error);
}
}

这是他们文档中的RapidAPI代码:

代码语言:javascript
复制
const fetchData = () => {
startFlip()
setLoading(true);
fetch('https://coin-flip1.p.rapidapi.com/headstails', {
"method": "GET",
"headers": {
  "x-rapidapi-host": "coin-flip1.p.rapidapi.org",
  "x-rapidapi-key": 'apikey'
}
})
.then((response) => response.json())
.then((json) => setData(json.outcome))
.catch(() => Alert.alert('Something went wrong..', 'There was an error fetching coin flip.'))
.finally(() => {
  setLoading(false)
  resetFlip()
});
};
EN

回答 1

Stack Overflow用户

发布于 2021-08-20 10:15:08

我假设你在RapidAPI上使用Coin Flip API。如果我使用axios,它对我来说工作得很好。

尝试使用此代码片段

代码语言:javascript
复制
var axios = require("axios").default;

var options = {
  method: 'GET',
  url: 'https://coin-flip1.p.rapidapi.com/headstails',
  headers: {
    'x-rapidapi-key': '12345',
    'x-rapidapi-host': 'coin-flip1.p.rapidapi.com'
  }
};

axios.request(options).then(function (response) {
    console.log(response.data.outcome);
}).catch(function (error) {
    console.error(error);
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64737301

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档