代理在 github 的已部署 React 项目中不工作,但在本地工作

proxy is not working in deployed react project to github but works locally

我有一个 React 项目,可以调用 Deezer API 来获取一些音乐信息。服务器的响应中没有 cors header。所以使用代理向 deezer 发出请求 api.i 在 package.json -

中设置了我的代理
 "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "predeploy":"npm run build",
    "deploy":"gh-pages -d build"
  },
  "proxy": "https://api.deezer.com",

我正在按如下方式进行 API 调用 -

 searchSongs= async ()=>{
         if(this.state.searchinput.length>2){
    const res = await fetch(`/search?q=${this.state.searchinput}`)
     const data = await res.json();
     console.log(data);
     this.setState({
       data:data.data
     },()=>{this.props.passSearchData(this.state.data)})
    }

它在本地主机上工作得很好,但在 github 上,我在控制台中得到了这个,也没有发出请求 -

获取https://prabhjot2002.github.io/api/search?q=mankirat404 VM39:1 未捕获(承诺)SyntaxError:意外标记 < in JSON 位置 0

https://prabhjot2002.github.io/musicplay/ - 这是 link 我在 github 上部署的项目。

我要提出请求的 URL 是 - https://api.deezer.com/search?query={music姓名}

我没有太多构建 React 项目的经验,我只是在学习它,请帮助我,提前谢谢你。

代理仅适用于开发(本地),在您的情况下,您可以明确地将 url 的基础添加到端点以解决问题。

                         //add this section directly here
const res = await fetch(`https://api.deezer.com/search?q=${this.state.searchinput}`)

这将使调用转到正确的 API 端点。

代理只有在本地环境和部署环境的基础url不同时才有用。