角度:将自定义HTTP响应标头添加到dev`ng serve` [英] Angular: add custom HTTP response headers to 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
- 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屋!