Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Angular proxy 配置 #50

Open
deepthan opened this issue Jun 16, 2020 · 0 comments
Open

Angular proxy 配置 #50

deepthan opened this issue Jun 16, 2020 · 0 comments

Comments

@deepthan
Copy link
Owner

Angular proxy 配置

本文将介绍如何基于脚手架配置 Angular 代理

为何做?

写一个代理文件,将匹配的请求代理到其他地址,解决本地开发跨域问题。

如何配置?

  • 在根目录中创建一个proxy.config.js
  • 可以在这个文件中做如下配置
  • 在 package.json的运行项目命令中加入 --proxy-config proxy.config.js

配置介绍

const PROXY_CONFIG = [
  {
    context: ['/api'],
    target: 'http://xxx',
    secure: false,
    changeOrigin: true,
    pathRewrite: {
      '^/api': '',
    },
  },
];
module.exports = PROXY_CONFIG;
  • context: 需要匹配的path
  • target: 代理到的地址
  • pathRewrite: 将请求的部分path重写,它是一个对象,键是^+要重写的path, 值是替换的path。
  • secure: 安全设置
  • changeOrigin: 改变源

配置实例


http://localhost:4208/auth/login

想要代理到

http://www.baidu.com/news/login

可以这样配置

const PROXY_CONFIG = [
  {
    context: ['/auth/login'],
    target: 'http://www.baidu.com',
    pathRewrite: {
        '^/auth/login': '/news/login',
    },
  },
  
]

module.exports = PROXY_CONFIG;

Q: 如果有两个接口,一个api/v1/1,另外一个api/v1/cer/login,我该如何将两个接口代理到不同的地址?

{
    context: ['api/v1/cer/login'],
    target: 'xxx1',
    secure: false,
    changeOrigin: true,
},
{
    context: ['/api'],
    target: 'xxx2',
    secure: false,
},

使用/api,只要是匹配到这个的都会走它的代理,不过如果在它前面加了个更加精确的api/v1/cer/login,会匹配到它,走这个代理。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant