前端代理解决跨越问题

在我的许多实际工程中,我并没有使用什么所谓前端代理去解决跨域问题,都是让运维大佬给我在配置里增加一下我的本机 ip。

今天乘着结束一个小项目的时候把玩下前端代理

  1. 首先我是用的技术栈是 react+antd+dva+umi,其中 umi 已经使用了 webpack-dev-server 插件 所以可以直接进行配置。
    如果你用的也是 umijs 这个 react 应用框架 可以直接使用如下配置

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    proxy: {
    '/u/v1/': {
    target: 'https://demo.xxx.com/',
    changeOrigin: true,
    // pathRewrite: { '^/u/v1/': '' },
    secure: false,
    },
    '/f/v1/': {
    target: 'https://demo.xxx.com/',
    changeOrigin: true,
    // pathRewrite: { '^/u/v1/': '' },
    secure: false,
    },
    },

    // /u/v1/ 用作匹配API地址 例如你要请求的API地址 是https://demo.xxx.com/u/v1/getUserInfo 含有/u/v1/这个字符串
    // 就会在发起请求时,将请求代理到本机地址====>https://localHost:8080/u/v1/getUserInfo

    // target 代理的API地址,就是需要跨域的API地址。
    // 地址可以是域名,如:https://demo.xxx.com/
    // 也可以是IP地址:http://127.0.0.1:3000
    // 如果是域名需要额外添加一个参数changeOrigin: true,否则会代理失败。

    //changeOrigin: true, 这个参数可以让target参数是域名。

    // secure: false,不检查安全问题。
    // 设置后,可以接受运行在 HTTPS 上,可以使用无效证书的后端服务器

    // API地址 为https://demo.xxx.com/u/v1/getUserInfo
    // 设置pathRewrite: {'^/u/v1/' : ''},后,
    // 最终本地代理访问的路径:https://localHost:8080/getUserInfo,
    // 这个参数的目的是给代理命名后,在访问时把命名删除掉。


    这个在config.js或者umirc.js 中配置好后即可快速检验下

    之后将api地址例如 BASE_HOST:http://192.168.2.240 改为 BASE_HOST:''

    默认你引入了各种请求工具 如axios fetch之类的


    // 假设 我的想跨域的地址为 https://demo.xxx.com/u/v1/getUserInfo
    // 只需填入/u/v1/getUserInfo

    axios({
    method: 'get',
    url: '/u/v1/getUserInfo', //填入你想跨域的api地址
    }).then((res)=>{
    console.log(res)
    });
  2. 没有使用 umi 也是一样的
    首先确保
    (1)、需要使用插件:webpack-dev-server。
    (2)、webpack-dev-server 使用的是 http-proxy-middleware 来实现跨域代理的。
    (3). webpack 版本 >= 3.0

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
module.exports = {
//...
devServer: {
proxy: {
"/u/v1/": {
target: "https://demo.xxx.com/",
changeOrigin: true,
// pathRewrite: { '^/u/v1/': '' },
secure: false
},
"/f/v1/": {
target: "https://demo.xxx.com/",
changeOrigin: true,
// pathRewrite: { '^/u/v1/': '' },
secure: false
}
// 还有需要匹配的就继续写...
}
}
};
PenZ wechat
交个朋友吧
点滴分享,您的支持将极大的鼓励我!