I’m facing an issue in my react application where I have created setupProxy.js file in that I have added multiple environment url (.development, .test) . Development port is running “http://localhost:8080 & test is running “/bizcomp.test.com”. When I run my app using test env (non-prod) its working properly but if I run my app using backend port (8080) path is not accepting. Please find below setupProxy.js & error screenshot.
Below is the api call which we use in frontend
http://localhost:8080/bizcomp/restservices/v1/service/seller/comptitle.
Note: Issue which I’m checking “/bizcomp” path in setupProxy is working. But I run my app using test env “/bizcomp” is working properly.
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function (app) {
let targetUrl;
// Set the target URL based on the current environment
if (process.env.NODE_ENV === 'development') {
targetUrl = "http://localhost:8080"
} else if (process.env.NODE_ENV === 'test') {
targetUrl = process.env.REACT_APP_OIDC_REDIRECT_URI;
} else {
console.error('Unknown environment:', process.env.NODE_ENV);
return;
}
console.log(`Proxying requests to: ${targetUrl}`);
// Proxy API requests to the backend server
app.use(
'/bizcomp',
createProxyMiddleware({
target: targetUrl,
changeOrigin: true,
secure: false, // Disable SSL verification if necessary
onProxyReq: (proxyReq, req, res) => {
console.log(`Proxying request: ${req.method} ${req.url}`);
},
onError: (err, req, res) => {
console.error('Proxy error:', err);
res.status(500).send('Proxy error');
},
})
);
};
7
The way http-proxy-middleware
works is by proxying the request path that comes after the base path provided and passing that to the upstream target
.
For example with
app.use('/bizcomp', createProxyMiddleware({
target: 'http://localhost:8080',
});
Only the part after /bizcomp
in the original request is sent
Original Request | Proxied Request |
---|---|
http://localhost:3000/bizcomp/foo/bar |
http://localhost:8080/foo/bar |
If you want to keep that base path in the proxied URL, you need to include it in the target
if (process.env.NODE_ENV === 'development') {
targetUrl = 'http://localhost:8080/bizcomp';
}
Unfortunately this is not well documented.
As an aside, Create React App is unmaintained and no longer a recommended option for starting React apps.
See this answer for some references and recommendations.
3