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. Due to security in the API, my response application cannot directly execute an ajax request to the endpoint. So I am trying to create a simple proxy as shown here

My package.json file as follows:

 { "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 he does nothing. I still get 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 basically have the same problem as documented here , where he is trying to create a proxy for accessing the Steam api.

And just a side note, I believe that the create-response-app project that I use is disconnected from webpack.

+5
source share
1 answer

You probably guessed it, but for others, this is what I:

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

therefore myreact.com/proxy/my/path redirected to mybackend.com/my/path

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

+1
source

Source: https://habr.com/ru/post/1272081/


All Articles