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

前端之家收集整理的这篇文章主要介绍了reactjs – 如何在React / Webpack中创建代理以调用外部API前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想向我无法控制的外部API发出GET请求.由于API的安全性,我的react应用程序无法直接向端点发出ajax请求.因此,我正在尝试创建一个简单的代理,如 here所示

我的package.json文件如下所示:

{
  "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
    }
  }
}

然后我的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);
  }
});

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

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

我基本上遇到了与here文档相同的问题,他试图创建一个代理来访问Steam api.

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

你可能现在已经知道了,但对于其他人来说这是有用的
我:
"proxy": {
    "/proxy": {
        "target": "https://mybackend.com","pathRewrite": {
                "^/proxy" : ""
        },"changeOrigin": true
    }
}

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

我认为您的错误是您将目标作为代理的密钥而不是反应服务器上的路径.

原文链接:https://www.f2er.com/react/300820.html

猜你在找的React相关文章