如何在React / Webpack中创建代理以调用外部API [英] How to create a proxy in React/Webpack to call an external API

查看:200
本文介绍了如何在React / Webpack中创建代理以调用外部API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to issue a GET request to an external API that I do not control. Because of the security on the API, my react app cannot directly make an ajax request to the endpoint. Therefore I'm trying to create a simple proxy as demonstrated 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请求如下所示:

And then my ajax request looks like this:

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);
  }
});

但是它似乎没有任何作用。我仍然收到以下错误:

But it doesn't appear to be doing anything. I'm still getting the following error:

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

我基本上遇到的问题与记录的此处,他试图在其中创建代理以访问Steam api。

I essentially have the same issue as documented here where he is trying to create a proxy to access the Steam api.

还有一点需要注意的是,我认为我正在使用的create-react-app项目是从webpack附带的。

And just a side note, I believe the create-react-app project that I'm using is piggybacking off of webpack.

推荐答案

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

You probably figured it out by now but for others here is what worked for me:

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

因此将 myreact.com/proxy/my/path 重定向到 mybackend.com/my/path

我认为您的错误是您将目的地作为代理的键而不是pat h在您的反应服务器上。

I think the error in your case is that you put the destination as a key for your proxy instead of path on your react server.

这篇关于如何在React / Webpack中创建代理以调用外部API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆