如何在React/Webpack中创建代理以调用外部API

rek*_*irt 7 proxy reactjs webpack create-react-app

我想向我无法控制的外部API发出GET请求.由于API的安全性,我的react应用程序无法直接向端点发出ajax请求.因此,我想创建一个简单的代理作为证明这里

package.json file看起来像这样:

{
  "name": "my-stack",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "react": "^15.6.1",
    "react-dom": "^15.6.1",
    "react-router-dom": "^4.2.2",
    "react-scripts": "1.0.13"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  },
  "proxy": {
    "https://gold-feed.com/paid/*": {
        "target": "https://gold-feed.com/paid",
        "changeOrigin": true
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

然后我的ajax请求看起来像这样:

const apiUrl = 'https://gold-feed.com/paid/<apiID>/all_metals_json_usd.php';

jQuery.ajax({
  method: 'GET',
  url: apiUrl,
  success: (item) => {
    this.props.addItem(item);
  }
});
Run Code Online (Sandbox Code Playgroud)

但它似乎没有做任何事情.我仍然收到以下错误:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.
Run Code Online (Sandbox Code Playgroud)

我基本上有与此处记录的相同的问题,他试图创建一个代理来访问Steam api.

只是旁注,我相信我正在使用的create-react-app项目正在捎带webpack.

小智 5

您可能现在已经知道了,但是对于其他人来说,这对我有用:

"proxy": {
    "/proxy": {
        "target": "https://mybackend.com",
        "pathRewrite": {
                "^/proxy" : ""
        },
        "changeOrigin": true
    }
}
Run Code Online (Sandbox Code Playgroud)

所以myreact.com/proxy/my/path被重定向到mybackend.com/my/path

我认为您遇到的错误是,您将目标位置作为代理的键,而不是反应服务器上的路径。