How to setup proxying in React and usage:
server:{
port:3000,
proxy:{
'/api':{
target:'http://localhost:3001',
changeOrigin:true,
rewrite:(path)=>path.replace(/^\/api/,'')
}
}, const fetchJobsData = async () => {
try {
const res = await fetch('/api/jobs');
const data = await res.json();
setJobs(data);
} catch (error) {
console.log('error fetching jobs', error);
} finally {
-
- This is the configuration object for the Vite development server.
-
port: 3000:- This sets the port on which the Vite development server will run. In this case, the server will be accessible at
http://localhost:3000.
- This sets the port on which the Vite development server will run. In this case, the server will be accessible at
-
- This is the configuration object for setting up a proxy. A proxy is used to forward requests from the Vite development server to another server.
-
'/api':- This specifies that any request starting with
/apishould be proxied.
- This specifies that any request starting with
-
target: 'http://localhost:3001':- This sets the target server to which the requests should be proxied. In this case, requests to
/apiwill be forwarded tohttp://localhost:3001.
- This sets the target server to which the requests should be proxied. In this case, requests to
-
rewrite: (path) => path.replace(/^\/api/, ''):- This function rewrites the URL path before forwarding it to the target server. In this case, it removes the
/apiprefix from the path. - For example, a request to
http://localhost:3000/api/jobswill be proxied tohttp://localhost:3001/jobs.
- This function rewrites the URL path before forwarding it to the target server. In this case, it removes the