Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to alter http request's header using javascript?

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

like image 504
thiagocfb Avatar asked Jun 26 '12 19:06

thiagocfb


People also ask

Can HTTP headers be modified?

You can manipulate the headers of incoming HTTP requests through HTTP Request Header Modification Rules. Through these rules you can: Set the value of an HTTP request header to a literal string value, overwriting its previous value or adding a new header to the request.

Can JavaScript access response headers?

Can I read response headers in JavaScript? While you can't ready any headers of HTML response in JS, you can read Server-Timing header, and you can pass arbitrary key-value data through it.

What are an HTTP requests header lines for?

HTTP headers let the client and the server pass additional information with an HTTP request or response. An HTTP header consists of its case-insensitive name followed by a colon ( : ), then by its value.


2 Answers

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' });
like image 73
zamnuts Avatar answered Oct 03 '22 22:10

zamnuts


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

like image 36
Greg Avatar answered Oct 03 '22 22:10

Greg