React Native,在源代码中使用RapidAPI

问题描述 投票:0回答:1

我曾经使用此代码来检索在我的 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()
});
};
javascript reactjs react-native security rapidapi
1个回答
1
投票

我假设您正在 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);
});
© www.soinside.com 2019 - 2024. All rights reserved.