Is it possible to alter http request's header

2019-02-17 09:00发布

Is it possible to use some kind of JavaScript to change or set a HTTP request's header?

2条回答
萌系小妹纸
2楼-- · 2019-02-17 09:28

Using the XMLHttpRequest object, you can use the setRequestHeader function.

A little code to get you on your way:

var xhr = new XMLHttpRequest()
xhr.open("GET", "/test.html", true);
xhr.setRequestHeader("Content-type", "text/html");

xhr.send();

The method setRequestHeader must be called after open, and before send.

More info: https://developer.mozilla.org/en/DOM/XMLHttpRequest#setRequestHeader()

查看更多
老娘就宠你
3楼-- · 2019-02-17 09:40

Headers are passed long before javascript is downloaded, let alone interpreted. The short is answer is no.

However, if you're speaking in the context of an ajax call (let's use jQuery as an example), the request headers can be written.

See reading headers from an AJAX call with jQuery. See setting headers before making the AJAX call with jQuery

However, if your javascript is server-side (e.g. node.js) that would be a yes (probably not since the post mentions HTML):

var body = 'hello world';
response.writeHead(200, {'Content-Length': body.length,'Content-Type': 'text/plain' });
查看更多
登录 后发表回答