角度:将自定义HTTP响应标头添加到dev`ng serve` [英] Angular: add custom HTTP response headers to dev `ng serve`

查看:162
本文介绍了角度:将自定义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:

  • https://github.com/angular/angular-cli/issues/15095
  • https://github.com/angular/angular-cli/issues/15729

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

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');
         };
    }
};

这篇关于角度:将自定义HTTP响应标头添加到dev`ng serve`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆