Angular:将自定义 HTTP 响应标头添加到 dev `ng serve`

问题描述:

是否可以向使用 ng serve 运行的开发服务器添加自定义 HTTP 响应标头?我想在主 html 文件请求的响应中专门添加这个自定义标头,尽管如果为每个资源(js 文件,等).

Is it possible to add a custom HTTP response header to the development server that runs with ng serve? I'd like to add this custom header specially in the response of the main html file request, although it'd fine if it was added for every resource (js files, etc.).

我发现了这两个最近的 Angular 问题:

I found these two recent Angular issues:

但我仍然不清楚是否有可能做到,以及是否有可能实现.

But it's still unclear to me if it's even possible to do it, and if it's possible how to accomplish it.

我添加了一个 proxy.config.js 文件(引用自 angular.json,部分 projects -> my-app -> Architect -> serve -> options -> proxyConfig) 并尝试了几种配置,如下所示,但没有成功:

I have added a proxy.config.js file (referenced from angular.json, section projects -> my-app -> architect -> serve -> options -> proxyConfig) and tried several configs, like the following one, with no luck:

module.exports = {
    "/": {
        'headers': {
            'X-Custom-Foo': 'bar'
        },
        onProxyRes: (proxyRes, req, res) => {
            proxyRes.headers['x-added'] = 'foobar';
        }
    },
    'headers': {
        'X-Custom-Foo': 'bar'
    },
    onProxyRes: (proxyRes, req, res) => {
        proxyRes.headers['x-added'] = 'foobar';
    }
};

是否可以在不使用第三方服务器的情况下这样做?

Is it possible to do so without having to use a third-party server?

假设您尝试模拟生产环境设置相同的响应标头值:您可以在代理配置中使用 bypass 代替onProxyRes.您不会尝试将调用重定向到另一台服务器(target 值)并在 onProxyRes 中处理答案,因此请避免使用它并尝试使用 bypass>.它应该可以正常工作;)

Assuming you're trying to simulate the production environment setting the same response header values: you could use bypass in the proxy configuration instead of onProxyRes. You are not trying to redirect the calls to another server (target value) and handle the answer in onProxyRes, so avoid using it and try with bypass. It should work fine ;)

proxy.conf.js 看起来像这样:

The proxy.conf.js would look something like this:

module.exports = {
  "/": {
    "secure": false,
    "bypass": (req, res, proxyOptions) => {
      res.setHeader('X-Header-Test', 'bacon');
    }
  }
};