Angular 根级代理

Angular Proxy in root level

我有一个 Angular 应用程序和一个用 jQuery 编写的登录页面。

我想在每次请求位于 http://mywebsite.com 的根目录时提供登陆页面。还有什么,比方说 http://mywebsite.com/otherpage,我想为 Angular 应用程序提供服务。

使用 nginx(生产),这相当容易。

在开发 Angular 时,我们可以使用 --proxy-config proxy.config.json CLI 选项轻松代理其他请求,例如 /api

我遇到的问题与根级别有关。

我做错了什么?我不能代理根级别吗?

Angular docs tells us to go to Webpack dev-server docs,但我还是不知道该怎么做。

我的proxy.config.json是这样的:

{
  "/api/*": {
    "target": "http://localhost:3000",
    "secure": false,
    "logLevel": "debug"
  },
  "/": {
    "index": "",
    "target": "http://localhost:3000",
    "secure": false,
    "logLevel": "debug"
  }
}

看来还是跟根级别冲突了

换到其他级别,我可以让它工作。

文档对此没有解释。

我得到了一个有效的代理配置,它只拦截根而不是 angular 与 baseHref 一起提供的应用程序。您需要使用 .js 配置 (https://angular.io/guide/build#proxy-multiple-entries) with an exclusion defined for http-proxy-middleware (https://github.com/chimurai/http-proxy-middleware#context-matching)。下面的配置代理每个以 /otherpage 开头的请求。 angular 应用程序应使用“/otherpage”作为 baseHref

const PROXY_CONFIG = [
  {
    context: [
      "/**",
      "!/otherpage**"
    ],
    "target": "http://localhost:3000",
    "secure": false,
  }
];

module.exports = PROXY_CONFIG;

如果您将 devServer.index 设置为假值,它会起作用。

https://webpack.js.org/configuration/dev-server/#devserver-proxy

Note that requests to root won't be proxied by default. To enable root proxying, the devServer.index option should be specified as a falsy value:

module.exports = {
    //...
    devServer: {
        index: '', // specify to enable root proxying
        host: '...',
        contentBase: '...',
        proxy: {
        context: () => true,
        target: 'http://localhost:1234'
        }
    }
};

我按如下方式使它工作:

angular.json中:

"architect": {
  "build": {
    "builder": "@angular-builders/custom-webpack:browser",
    "options": {
      "customWebpackConfig": {
        "path": "./my-custom-webpack.config.js"
      },

  ...

  "serve": {
    "builder": "@angular-builders/custom-webpack:dev-server",
    "options": {
      "proxyConfig": "webpack-proxy.conf.js",

  ...

my-custom-webpack.config.js中:

module.exports = {
  ...
  devServer: {
    index: '' // Allows us to proxy the root URL
  }
}

webpack-proxy.conf.js

const PROXY_CONFIG = [{
  context: [
    '/'
  ],
  target: 'http://proxy-to-url',
  bypass: function(request) {
    // proxy the root URL, plus "/api/*" - otherwise serve using Angular
    return /^\/(api\/.*)?$/.test(request.url) ? null : '/index.html';
  },
  secure: false
}];

module.exports = PROXY_CONFIG;

(需要 @angular-builders/custom-webpack 安装:npm i -D @angular-builders/custom-webpack