首页 > 解决方案 > React Native,在源代码中使用 RapidAPI

问题描述

我曾经有这段代码来检索我的 React Naive 源代码中包含个人数据的 JSON 文件:

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 让它更安全,但我不知道如何使用它,它给了我没有数据的白页:这是我修改后的代码:

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 代码:

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()
});
};

标签: javascriptreactjsreact-nativeapisecurity

解决方案


我假设您在 RapidAPI 上使用Coin Flip API 。如果我使用 axios,它对我来说工作正常。

尝试使用此代码段

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);
});

推荐阅读