http-proxy-middleware代理转发到不同的IP和端口

http-proxy-middleware一个轻松的配置代理服务器的中间件

开发中若接口文档中接口有不同的IP和端口号,需要在option下的router属性中配置path:转向的端口和IP,我这里使用的是path来匹配请求。参考文档:http-proxy-middleware

/**
 * @file config for proxy, useful only in dev.
 *
 * @author taohang(taohang@baidu.com)
 *
 * The dev server is using http-proxy-middleware for proxying,
 * so you can refer to its docs for detailed usage.
 * see https://github.com/chimurai/http-proxy-middleware for documentation.
 */

module.exports = {
    proxy: {
        // proxy all requests starting with /api to target,
        // use /*/* will proxy all requests starting with any string
        // proxy useful only while path exist && option.target is exist
        path: ['/eam/asset/', '/currentUser', '/eam/host/', '/eam/', '/platform/api/v1', '/apptree/v1',
            '/apptreeNew', '/asset',
            '/eam_task', '/taskNames', '/intervals', '/status', '/tasks', '/columns', '/network/subnet/physical'],
        option: {
            // the target to request
            // target: 'http://10.130.71.24:8050',		// 上线地址
            // target: 'http://10.132.144.17:8009',   	// 测试地址
            // target: 'http://10.132.144.17:8050',  	// 物理机资产地址
            target: 'http://10.132.144.31:8010',  		// 资产测试地址
            // changes the origin of the host header to the target URL
            changeOrigin: true,
            // object, adds request headers. (Example: {Cookie:'mycookie'})
            headers: {
                // get cookie by visit the target url
                Cookie: ''
            },
            // 这里表示不同的path对应不同的转发 path: url
            router: {
                '/network/subnet/physical': 'http://10.132.144.31:8009'
            }
        }
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
使用 Proxy 代理可以解决前端跨域问题,具体步骤如下: 1. 在前端项目中,配置一个代理服务器,比如使用 http-proxy-middleware 或者 http-proxy 等库来实现。 2. 在配置中指定代理服务器的目标地址,以及需要代理的 API 地址。 3. 在前端代码中,使用代理服务器的地址来访问 API,而不是直接访问 API 地址。 例如,假设前端代码需要访问一个 API,地址为 http://api.example.com/data,但是由于浏览器的同源策略限制,无法直接访问该 API。为了解决这个问题,可以配置一个代理服务器,将 http://api.example.com/data 发送到代理服务器上,再由代理服务器转发请求到目标地址。 具体实现方式示例如下: ``` const express = require('express'); const { createProxyMiddleware } = require('http-proxy-middleware'); const app = express(); app.use('/api', createProxyMiddleware({ target: 'http://api.example.com', changeOrigin: true })); app.listen(3000, () => { console.log('Proxy server is running on http://localhost:3000'); }); ``` 上述代码使用了 express 库来创建一个代理服务器,将以 /api 开头的请求代理http://api.example.com 上,并启动代理服务器在本地的 3000 端口上。 在前端代码中,可以使用代理服务器的地址来访问 API,例如: ``` axios.get('/api/data') ``` 上述代码中,axios 库会将 /api/data 发送到代理服务器上,代理服务器再将请求转发http://api.example.com/data 上,并将结果返回给前端代码。这样就可以避免浏览器的同源策略限制,实现跨域访问 API。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值