[英]Setting header value from Javascript Client Side
I want to set a customer header from browser similar to what mod plugin does on chrome, is there any way to set a header from javascript client side?我想从浏览器中设置一个客户 header,类似于 chrome 上的 mod 插件,有没有办法从 javascript 客户端设置 header?
Based on a condition, I want to set a header so that all subsequent browser requests will have this header value.根据一个条件,我想设置一个 header 以便所有后续浏览器请求都具有这个 header 值。
I know this from server side, but wanted to know if it is possible from client side.我从服务器端知道这一点,但想知道从客户端是否有可能。
A simple way to do this in vanilla JS is to augment the XMLHTTPRequest.prototype.send
method.在 vanilla JS 中执行此操作的一个简单方法是增加
XMLHTTPRequest.prototype.send
方法。
You would do something like你会做类似的事情
const defaultSend = XMLHTTPRequest.prototype.send;
XMLHTTPRequest.prototype.send = function (data) {
this.setRequestHeader('SOME-CUSTOM-HEADER', 'header-value');
defaultSend.call(this, data);
};
While this works, it's like using a nuke when you need a hammer.虽然这行得通,但就像在需要锤子时使用核武器一样。 It pollutes ALL of the following XHRs run in the context of that particular window.
它污染了在特定 window 的上下文中运行的以下所有 XHR。 While you could do domain level filtering, but I find that it's not worth the trouble.
虽然您可以进行域级别过滤,但我发现这不值得麻烦。
If you are using client XHR libraries like axios , they will often provide a better and more contextual way.如果您使用axios等客户端 XHR 库,它们通常会提供更好、更符合上下文的方式。 For example, in case of axios, you could do something like
例如,在 axios 的情况下,您可以执行类似的操作
const client = axios.createClient();
client.interceptors.request.use(config => {
config.headers['SOME-CUSTOM-HEADER'] = 'header-value';
return config;
});
client.get('/some-url', params); // this will have the custom header that you injected
EDIT: One caveat here is that this only affects XHRs, not form submissions or asset calls.编辑:这里的一个警告是,这只会影响 XHR,而不是表单提交或资产调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.