【问题标题】:How to create a proxy in React/Webpack to call an external API如何在 React/Webpack 中创建代理以调用外部 API
【发布时间】:2018-03-05 18:02:06
【问题描述】:

我想向我无法控制的外部 API 发出 GET 请求。由于 API 的安全性,我的 react 应用程序无法直接向端点发出 ajax 请求。因此,我正在尝试创建一个简单的代理,如 here

所示

我的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
    }
  }
}

然后我的 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 捎带而来的。

【问题讨论】:

  • 你的问题很有趣,我不是 React 方面的专家,但是,似乎没有代理配置,浏览器正在执行请求,当然,CORS 策略被应用。自己完成的方法应该是,在节点中公开一个Rest API,并且是请求者对api的后端,而我的前端只与我的后端通信,所以前端不关心第三方api的CORS问题。在 react/redux 架构中使用 axios 可能会解决问题,但我不太确定
  • 我也遇到过同样的问题,但我只是通过 "proxy": "https://gold-feed.com/paid/" } 解决了这个问题。可以这样试试吗?
  • 我会试试的。你把它放在 package.json 中?
  • 如果您使用 webpack-dev-server,请尝试在 webpack.config.js 中使用devServer: { proxy: { 'https://gold-feed.com/': { target: 'https://gold-feed.com/', secure: false } } }
  • @Matthew Barbara 不幸的是,这对我不起作用。除了 package.json 中的那一行之外,您是否需要更改其他任何内容?您是否必须在其他任何地方引用代理?谢谢!

标签: reactjs webpack proxy create-react-app


【解决方案1】:

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

"proxy": {
    "/proxy": {
        "target": "https://mybackend.com",
        "pathRewrite": {
                "^/proxy" : ""
        },
        "changeOrigin": true
    }
}

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

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

【讨论】:

  • 嗨,我已经尝试了一天,但似乎根本不起作用。使用 create-react-app 但我们已经弹出。在包 json 中添加一个代理对象,其中包含要匹配的应用服务器路径端点,以及要命中的外部服务作为目标。该应用程序仍然试图打一条不存在的本地路线......也许我错过了一个在任何地方都没有明确记录的步骤?或者,过去我使用带有 http-proxy 的 express 应用程序来解决这些 CORS 问题,并且非常简单。
【解决方案2】:

对于我的情况,我的 api 部署在 AWS 上,我发现设置

"changeOrigin": true

是必要的(chrome 和 edge 工作,firefox (62.0.3) 抱怨“无效的 CORS 请求”)。

在 webpack http 代理的文档中,他们说这个选项: (https://github.com/chimurai/http-proxy-middleware)

提示:对于基于名称的虚拟托管站点,请将选项 changeOrigin 设置为 true。

注释:

  • 在同一台机器上本地运行 api 不需要火狐。
  • firefox 添加了标头“origin”,当我删除并重新发送请求时该标头有效。
  • 添加“changeOrigin”没有副作用,所以我将从现在开始这样做。

我不确定这是 Firefox 的错误还是什么,反正我的最终配置是:

"proxy": {
  "/api": {
    "target": "<put ip address>",
    "changeOrigin" : true
  }
}

您应该将 /api 替换为您的 api 的路径或将路径重写为上述答案。

【讨论】:

    【解决方案3】:

    您可以将外部 API 代理到 localhost,更改前端来源 (localhost:3000)、目标服务器、更新令牌(如果需要)并在节点 js 中运行以下脚本

    const express = require('express');
    const proxy = require('express-http-proxy');
    const cors = require("cors");
    
    const app = express();
    
    app.use(
      cors({
        origin: 'localhost:3000',
        credentials: false
      })
    );
    
    app.use('/', proxy('https://www.targetserver.com/', {
      proxyReqPathResolver: function (req) {
        return req.url;
      },
      proxyReqOptDecorator: function (proxyReqOpts, srcReq) {
        proxyReqOpts.headers = {'Authorization': 'Replace with JWT'};
        return proxyReqOpts;
      }
    }))
    
    app.get('/*',function(req,res,next){
      res.header("Access-Control-Allow-Origin", "*");
      res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
      next();
    });
    
    
    app.listen(4000, () => console.log(`Server Listening on port ${4000}!`));
    

    像这样在你的字体应用程序中使用它(使用 axios 或 fetch):

    axios.get('http://localhost:4000/api/route).then(x => console.log(x));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-25
      • 2019-09-08
      • 2016-01-04
      • 2016-03-13
      • 1970-01-01
      • 1970-01-01
      • 2016-05-30
      • 2015-11-18
      相关资源
      最近更新 更多