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

查看:52
本文介绍了如何在 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 文件 看起来像这样:

My package.json file looks like this:

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

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

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天全站免登陆