简体   繁体   中英

proxy not working for create-react-app in production

I am working with reactjs( create-react-app ) to create a dashboard application, In my application i am calling multiple host ( for that I have configured multiple proxies in package.json to avoid CORS ). ex- www.app.demo1.com, www.app.demo2.com, www.app.demo3.com...

"proxy": {
    "/demo1/api/":{
  "target":"www.app.demo1.com"
},
"/demo2/api/":{
  "target":"www.app.demo2.com"
},
"/demo3/api/":{
  "target":"www.app.demo3.com"
}
}

in application i am calling like-

try{
   const host1 = process.env.NODE_ENV === 'production'? 
   'www.app.demo1.com/demo1/api': '/demo1/api/';
   const host2 = process.env.NODE_ENV === 'production'? 
   'www.app.demo2.com/demo2/api': '/demo2/api/';
   const host3 = process.env.NODE_ENV === 'production'? 
  'www.app.demo3.com/demo3/api': '/demo3/api/';
   const resp1 = axios.get(host1)
   const resp2 = axios.get(host2)
   const resp3 = axios.get(host3)
}catch(){}

in development: when making request to /demo1/api/ it is being proxied to www.app.demo1.com/demo1/api and i am getting the response. but

in production: I have deployed the application on github pages, although I am getting the below error, enter image description here

Can anybody help..

Proxies are for development purposes only, and they are handled by webpack-dev-server . On production you need to make the calls to the actual host.

This is created because usually, on development, react is served by a standalone server meant just for that (hence, webpack-dev-server ). On production, usually there is a backend (node? ruby? php?) that serves the pages and every call made is going to be to some endpoint with the same hostname.

Example:

In your development environment you have a node server running on port 3001 and your react code running on port 3000. When react fetches /api/user , you actually want http://localhost:3001/api/user , which points to your node server.

In your production environment, you have a server (nginx, maybe?) that forwards all /api calls to your node process, and for everything else it serves your react main index.html file (so you can use react-router , for example). In this case, whenever you request /api/user , this is going to be handled by your web server and routed properly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM