配置本地代理转发,解决跨域问题

本文详细介绍了如何在React项目中使用http-proxy-middleware进行代理配置,包括安装中间件、创建配置文件、设置代理规则及常见问题解决方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第一步:安装http-proxy-middleware
$ npm install http-proxy-middleware --save
$ # or
$ yarn add http-proxy-middleware
第二步:创建`src/setupProxy.js`,配置内容如下
const proxy = require("http-proxy-middleware");

module.exports = function (app) {
    app.use(proxy("/apps/analysis/**", {
        target: "http://10.154.2.119:9000/",
        changeOrigin: true
    }));
    app.use(proxy("/apps/access/**", {
        target: "http://10.154.2.119:9000/",
        changeOrigin: true
    }));
    app.use(proxy("/apps_laravel/yq/analysis/**", {
        target: "http://10.154.2.119:9000/",
        changeOrigin: true
    }));
};
请求接口的基地址如下:
let baseUrl = '/apps/analysis/';
let baseAccessUrl = '/apps/access/';
let lavarelBaseUrl = '/apps_laravel/yq/analysis/';
let baseStaticUrl = 'http://localhost:3000/';
第三步:重新编译运行,出现Proxy created表示代理转发成功。
遇到的问题:
第三步没有成功,则手动配置
1.在config/paths.js添加

2. config/webpackDevServer.config.js中修改



如下是react项目自带的配置代理的说明:
### Configuring the Proxy Manually

> Note: this feature is available with `react-scripts@2.0.0` and higher.

If the `proxy` option is **not** flexible enough for you, you can get direct access to the Express app instance and hook up your own proxy middleware.

You can use this feature in conjunction with the `proxy` property in `package.json`, but it is recommended you consolidate all of your logic into `src/setupProxy.js`.

First, install `http-proxy-middleware` using npm or Yarn:

```bash
$ npm install http-proxy-middleware --save
$ # or
$ yarn add http-proxy-middleware
```

Next, create `src/setupProxy.js` and place the following contents in it:

```js
const proxy = require('http-proxy-middleware');

module.exports = function(app) {
  // ...
};
```

You can now register proxies as you wish! Here's an example using the above `http-proxy-middleware`:

```js
const proxy = require('http-proxy-middleware');

module.exports = function(app) {
  app.use(proxy('/api', { target: 'http://localhost:5000/' }));
};
```

> **Note:** You do not need to import this file anywhere. It is automatically registered when you start the development server.

> **Note:** This file only supports Node's JavaScript syntax. Be sure to only use supported language features (i.e. no support for Flow, ES Modules, etc).

> **Note:** Passing the path to the proxy function allows you to use globbing and/or pattern matching on the path, which is more flexible than the express route matching.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值