













In a micro frontend project, unfortunately, I'm facing an issue. I want to access my React 17 project as a sub - project in my parent project, but it's blocked by the Cross - origin policy.
Thankfully, there's a solution. I configure the Create React App (CRA) development server to send the Access - Control - Allow - Origin header directly. This simple yet effective configuration is extremely useful if you want to expose your development server as a simple API endpoint for other clients to access without a separate backend server during development.
Here's how you can do it using the src/setupProxy.js file:
Create src/setupProxy.js (if it doesn't exist): In your project's src directory, create a file named setupProxy.js.
Add the following code:
\src\setupProxy.js
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
app.use(
'/', // Apply to all routes of the dev server
(req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*'); // Allow requests from any origin
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS'); // Specify allowed methods
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization'); // Specify allowed headers
next();
}
);
};
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。