首页 > 解决方案 > 已部署的 React 项目上的 HTTPS 错误

问题描述

我试图在 GH Pages 上托管我的 React 项目。部署工作正常,但是当我尝试搜索 gif 时出现以下错误

http_browser.js:47 Mixed Content: The page at 
'https://pimmesz.github.io/react-giphy/' was loaded over HTTPS, but 
 requested an insecure XMLHttpRequest endpoint 
'http://api.giphy.com/v1/gifs/search? 
q=h&limit=10&rating=g&api_key=MYAPIKEY'. This request has been blocked; the 
content must be served over HTTPS.

似乎 Giphy API 正在发出http请求而不是https. 有没有办法更改 API 使用的默认 url?

import React, { Component } from 'react';

import giphy from 'giphy-api';

import Search from './search.jsx';
import Gif from './gif.jsx';
import GifList from './gif_list.jsx';

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      gifs: [],
      gif: "xBoysJgwhLEZtAjbY1"
    }
  }

  search = (query) => {
    giphy('APIKEY').search({
      q: query,
      limit: 10,
      rating: 'g'
    }, (err, res) => {
      this.setState({gifs: res.data})
    });
  }

  select = (id) => {
    this.setState({gif: id})
  }


  render() {
    const gifs = this.state.gifs;
    return (
      <div>
        <div className="left-scene">
          <Search search={this.search}/>
          <Gif id={this.state.gif} select={this.select}  />
        </div>
        <div className="right-scene">
          <GifList gifs={gifs} select={this.select} />
        </div>
      </div>
    );
  }
}

export default App;

标签: reactjsapigiphy-api

解决方案


将 giphy API 执行更改为

const url = `https://api.giphy.com/v1/gifs/search?q=${query}&limit=10&rating=g&api_key=MY_API_KEY`
      fetch(url)
      .then(results => { return results.json();
      }).then(data => {
        this.setState({gifs: data.data});
      });

编辑

找到了另一种方法!

将 https 设置为 true 可以作为 giphy api 调用中的一个选项来完成

giphy({ apiKey: "MY_API_KEY", https: true })


推荐阅读