Configuring a Proxy in a React Project Using http-proxy-middleware
This article walks through setting up and debugging a CORS‑handling proxy in a React 18 project with create‑react‑app, using http‑proxy‑middleware to forward /api requests, configure logging, and verify the real request paths.
During recent React development I encountered a CORS issue that is usually solved on the backend; due to special circumstances I had to handle it on the frontend, so I documented the whole configuration process for future reference.
Environment
Project created with create-react-app; React v18.2.0
Using http-proxy-middleware v2.0.6
Operation Process
The prefix proxy is implemented with http-proxy-middleware v2.0.6.
1. Install the proxy plugin
npm install http-proxy-middleware --save2. Configure the proxy and debug
(1) Add setupProxy.js file
Note: This file must be placed under the src directory.
(2) Proxy configuration
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function (app) {
app.use(
createProxyMiddleware('/api', {
target: 'http://192.168.3.11:5000',
changeOrigin: true,
// Remove the prefix so the backend receives a normal path
pathRewrite: { '^/api': '/api' },
}),
// You can configure multiple proxies
createProxyMiddleware('/2api', {
target: 'http://192.168.3.11:6000',
changeOrigin: true,
pathRewrite: { '^/2api': '' },
})
);
};(3) Interface debugging
Example using a project‑specific localAxiosInstance (a wrapper around axios).
import { localAxiosInstance } from '@/axios/localTestAxios';
export const testApiProxy = () => {
return localAxiosInstance.get('/services/admin/SystemDic/GetPageSystemChannel', {
params: { MaxResultCount: 10, SkipCount: 0 },
});
};The localAxiosInstance is created as follows:
let localAxiosInstance = axios.create({
baseURL: LOCAL_TEST_URL, // constant value is '/api'
timeout: 1000 * 60,
/**
* Indicates whether credentials (cookies) should be sent with cross‑origin requests.
*/
withCredentials: true,
});(4) Test whether the proxy works
Run the project and check if the API call succeeds.
(5) View the real request path after proxying
http-proxy-middlewareprovides two useful options: logLevel: string, one of 'debug', 'info', 'warn', 'error', 'silent' onProxyReq: function, subscribes to the underlying
http-proxy proxyReqevent.
Updated setupProxy.js with logging:
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function (app) {
app.use(
createProxyMiddleware('/api', {
target: 'http://192.168.3.11:5000',
changeOrigin: true,
pathRewrite: { '^/api': '/api' },
logLevel: 'debug',
onProxyReq: (proxyReq, req) => {
console.log('[HPM] %s %s %s %s', req.method, req.originalUrl, '->', req.url);
},
}),
createProxyMiddleware('/2api', {
target: 'http://192.168.3.11:6000',
changeOrigin: true,
pathRewrite: { '^/2api': '' },
})
);
};Note: After modifying the configuration, restart the development server. The console in VSCode will now display the logged proxy requests.
Conclusion
We have completed the proxy configuration for a React project, demonstrating that the process is straightforward once the steps are clear. This summary serves as a personal record and a reference for anyone facing similar CORS challenges.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Rare Earth Juejin Tech Community
Juejin, a tech community that helps developers grow.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
