React17 , CRA项目添加Access-Control-Allow-Origin header

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:

  1. Create src/setupProxy.js (if it doesn't exist): In your project's src directory, create a file named setupProxy.js.

  2. Add the following code:

  3. Restart your dev server

 

\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();
    }
  );
};

  

posted @ 2025-04-14 10:47  zyip  阅读(18)  评论(0)    收藏  举报