惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

小众软件
小众软件
V
Visual Studio Blog
博客园 - 三生石上(FineUI控件)
Last Week in AI
Last Week in AI
Blog — PlanetScale
Blog — PlanetScale
爱范儿
爱范儿
J
Java Code Geeks
A
About on SuperTechFans
F
Fortinet All Blogs
B
Blog
aimingoo的专栏
aimingoo的专栏
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Engineering at Meta
Engineering at Meta
Y
Y Combinator Blog
有赞技术团队
有赞技术团队
G
Google Developers Blog
Apple Machine Learning Research
Apple Machine Learning Research
V
V2EX
博客园_首页
博客园 - 叶小钗
罗磊的独立博客
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
D
Docker
云风的 BLOG
云风的 BLOG

博客园 - zyip

超越2028:我们这一代,是末代普通程序员 中国生成式AI民用开荒史:2022–2023 icon资源 python几类安装方法 pyautogui 深入理解 CSS 中的 BFC wpf mvvm(prism) wpf 打包成单文件 vite 读取router mysql ensp run Python asyncio code in a Jupyter notebook 实现两个socket server 黑苹果 Sublime Text4 4143版本激活 comfyUI相关 wpf data binding windows命令行批量给文件名加前缀 unable to resolve dependency tree
React17 , CRA项目添加Access-Control-Allow-Origin header
zyip · 2025-04-14 · via 博客园 - zyip

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