相关疑难解决方法(0)

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

我想向我无法控制的外部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' …
Run Code Online (Sandbox Code Playgroud)

proxy reactjs webpack create-react-app

7
推荐指数
1
解决办法
8613
查看次数

标签 统计

create-react-app ×1

proxy ×1

reactjs ×1

webpack ×1