Webpack dev proxy not working - ReactJS

I want to run my project on localhost: 3000 / upct / ROUTES

But I have my API in: http://desarrollo.com/api

I want to use the proxy option in Webpack, but it does not work. I get a CORS error and others ... My proxy configuration looks like this:

CONFIG.devServer = { //host: 'localhost', port: 3000, proxy: { '/api/**': { target: 'http://desarrollo.com/api', secure: false, changeOrigin: true } }, contentBase: PATH.join(__dirname, '/src'), hot: true, inline: true, historyApiFallback: true/*, headers: { 'Content-Type': 'text/plain', 'Access-Control-Allow-Origin' : '*', 'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE' }*/ }; 

I execute my AJAX requests, for example:

  $.ajax({ url: "http://desarrollo.com/api", data: "", type:"GET", dataType: "JSON", }) .done((respuesta) => { console.log(respuesta); }).fail(function(xhr, textStatus, errorThrown){ console.log("XHR: ", xhr/*.responseText*/, "Text Status: ", textStatus + '\n' + "Error Thrown: ", errorThrown); }) 

I supposse proxy is designed to execute AJAX requests in my API without CORS errors. But that does not work. What is wrong here?

Thanks.

+1
reactjs webpack webpack-dev-server
source share
2 answers

When using a proxy server, you need to send your requests to localhost so that the proxy server can redirect them to a remote server without CORS. In your $.ajax() pass url: "/api" .

After that, when you launch the application locally, your requests will be sent to http://localhost:3000/api , and when it runs on http://desarrollo.com , it will send requests to http://desarrollo.com/api

+2
source share

To add more to @GProst's answer, there will be changes below.

Find protocol:

 this.protocol = () => { let returnValue = 'https://'; if (location.protocol !== 'https:') { returnValue = 'http://'; } return returnValue; }; 

Find host name:

 const hostName = window.location.hostname + (!window.location.port === false ? ':' + window.location.port : ''); 

Required URL:

 const URL = this.protocol() + hostName; 

Now the above URL can be used in Ajax.

 $.ajax({ url: URL, data: "", type:"GET", dataType: "JSON", }) 

This will work in both webpack-dev-server and application server, for example. Apache

0
source share

All Articles