Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
983 views
in Technique[技术] by (71.8m points)

reactjs - How to create a proxy in React/Webpack to call an external API

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

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

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.

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

so myreact.com/proxy/my/path is redirected to 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...