Angular: add custom HTTP response headers to dev `ng serve`

落爺英雄遲暮 提交于 2020-04-30 11:06:53

问题


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.).

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.

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?


回答1:


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

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

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


来源:https://stackoverflow.com/questions/59266224/angular-add-custom-http-response-headers-to-dev-ng-serve

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!