秘密通道:配置CRACO以启用反向代理跨域。

1,655 阅读1分钟

流动的水没有形状,漂流的风找不到踪迹,任何案件的推理都取决于心.

尽管现在并不推荐使用 CRA 脚手架,但,水贴的心常在

因为不建议使用 eject 弹出 CRA 的 webpack 配置(该操作不可逆),所以选择使用 Craco 来拓展 CRA 的 webpack 配置。(当然,使用 react-app-rewired 也是可以的。)

解决方案

Craco 配置解决跨域(推荐)

版本关系

react-scripts versionCRACO version
5.x.x (latest)7.0.0
4.x.x6.4.5
< 4.0.05.8.0

安装依赖

yarn add @craco/craco // npm i -D @craco/craco 

修改 package.json

"scripts": {
-  "start": "react-scripts start"
+  "start": "craco start"
-  "build": "react-scripts build"
+  "build": "craco build"
-  "test": "react-scripts test"
+  "test": "craco test"
}

新建文件

以下类型都支持

  1. craco.config.ts
  2. craco.config.js
  3. craco.config.cjs
  4. .cracorc.ts
  5. .cracorc.js
  6. .cracorc
  • target: 表示的是代理到的目标地址
  • pathRewrite:默认情况下,我们的/api-hy也会被写到 URL 中,如果希望删除,可以使用 pathRewrite
  • changeOrigin: 它是表示是否更新代理后请求的 headers 中的 host 地址
// 配置
devServer: {
  proxy: {
    "/api": {
      target: "API_SERVER_ADDRES", // 例如 http://192.168.0.42:9090
        changeOrigin: true,
        pathRewrite: {
        "^/api": "",
          },
    },
  },
},
// craco.config.cjs 完整配置
module.exports = {
	webpack: {
		// ...
	},
	devServer: {
		proxy: {
			"/api": {
				target: "http://api.data.ielee.com/",
				// target: "http://192.168.0.42:9090",
				changeOrigin: true,
				pathRewrite: {
					"^/api": "",
				},
			},
		},
	},
};

http-proxy-middleware 中间件

const { createProxyMiddleware } = require('http-proxy-middleware');

const apiProxy = createProxyMiddleware({
  target: 'http://www.example.org',
  changeOrigin: true,
});

// 'apiProxy' is now ready to be used as middleware in a server.

package.json(不推荐)

proxy 端口值后面不带/,在请求时需要在根路径携带/

{
  "name": "your-app",
  "version": "0.1.0",
  "proxy": "http://localhost:5000",
  ...
}
fetch('/api/data')
  .then(response => response.json())
  .then(data => console.log(data));
axios.get('/api/data')
  .then(response => console.log(response.data));

跨域原理