This is a unique situation, because I need to respond with CORS headers from a server, but the server is a create-react-app server running a react app.
I have 2 react applications, app1 (port 3002), app2 (port 3001) and 1 backend (port 3000). When I make a request from app1 to the backend (/api), it sends a 302 redirect to app2. This causes the browser to throw a CORS error because app2 doesn't respond to the preflight OPTIONS request with the access-control-allow-origin header. Is there a way to configure the CRA dev server to respond with this header? Or maybe these headers can be added via some proxy on app1?
Error
Access to XMLHttpRequest at 'http://localhost:3001/' (redirected from 'http://localhost:3002/api') from origin 'http://localhost:3002' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I've tried this on app1 with no luck:
src/setupProxy.js
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
app.use(
'/api',
createProxyMiddleware({
target: 'http://localhost:3000',
changeOrigin: true,
onProxyRes: response => {
response.headers['access-control-allow-origin'] = 'http://localhost:3002';
},
})
);
};
I'm guessing maybe I need to add some config to the server on app2 so it will respond to the preflight request, but I don't know how.
Update:
I found the node_modules/react-scripts/config/webpackDevServer.config.js and added
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS",
"Access-Control-Allow-Headers": "X-Requested-With, content-type, Authorization"
},
This adds the headers to the CORS request, but not really a permanent solution. I imagine I have to use craco to do this?