9

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

Anders
  • 8,307
  • 9
  • 56
  • 88
thiagocfb
  • 487
  • 1
  • 9
  • 19
  • 3
    @Thiago, When you say "html", you mean "http". HTML is the format of the text returned from the HTTP Request. Also, are you referring to an asynchronous request (i.e., ajax) or by a request that is made by the browser (for example, when the user clicks a link and the browser sends a request for the new resource). – Mark Hildreth Jun 26 '12 at 19:42
  • Originally i mean't the request made by the browser after a link is clicked, however ajax might solve my problem as well. Sorry about the mistake there with html / http x.x – thiagocfb Jun 26 '12 at 19:55

2 Answers2

11

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' });
Community
  • 1
  • 1
zamnuts
  • 9,492
  • 3
  • 39
  • 46
  • 1
    Saying Html was a mistake of mine, it is server-side, i believe your answer will help me a lot ! Thanks !! – thiagocfb Jun 26 '12 at 19:58
11

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

Greg
  • 21,235
  • 17
  • 84
  • 107