Home  >  Article  >  Web Front-end  >  A brief analysis of how to configure Angular proxy based on scaffolding

A brief analysis of how to configure Angular proxy based on scaffolding

青灯夜游
青灯夜游forward
2021-11-10 10:49:171621browse

This article will introduce to you how to configure the Angular proxy (proxy) based on scaffolding. I hope it will be helpful to you!

A brief analysis of how to configure Angular proxy based on scaffolding

Angular proxy configuration

  • Official website document https://angular.io/guide/build#using-corporate -proxy

[Related tutorial recommendation: "angular tutorial"]

Why do it?

Write a proxy file to proxy matching requests to other addresses to solve cross-domain problems in local development.

How to configure?

  • Create a proxy.config.js in the root directory
  • You can make the following configuration in this file
  • In Add --proxy-config proxy.config.js

## to the running project command of package.json

const PROXY_CONFIG = [
  {
    context: ['/api'],
    target: 'http://xxx',
    secure: false,
    changeOrigin: true,
    pathRewrite: {
      '^/api': '',
    },
  },
];
module.exports = PROXY_CONFIG;

  • context: The path that needs to be matched
  • #target: The address to be proxied to
  • pathRewrite: The requested part path rewriting, it is an object, the key is ^ the path to be rewritten, and the value is the path to be replaced.
  • secure: Security settings
  • changeOrigin: Change origin

Configuration instance

For example,

http://localhost:4208/auth/login

want to be proxied to

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

can be configured like this

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

module.exports = PROXY_CONFIG;

Q: If there are two interfaces, one/api/cer/register, the other A /api/cer/login, how can I proxy the two interfaces to different addresses?
{
    context: ['/api/cer/login'],
    target: 'xxx1',
    secure: false,
    changeOrigin: true,
},
{
    context: ['/api'],
    target: 'xxx2',
    secure: false,
},

Use

/api, as long as it matches this, it will go through its proxy, but if you add a more accurate /api/cer in front of it /login will match it first and use this proxy.

More usage updates on github:

https://github.com/deepthan/blog-angular

More programming related knowledge, Please visit:

Introduction to Programming! !

The above is the detailed content of A brief analysis of how to configure Angular proxy based on scaffolding. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete