Set a Request Header in JavaScript

Set a request header in JavaScript

W3C Spec on setrequestheader.

The brief points:

If the request header had
already been set, then the new value
MUST be concatenated to the existing
value using a U+002C COMMA followed by
a U+0020 SPACE for separation.

UAs MAY give the User-Agent header an initial value, but MUST allow authors to append values to it.

However - After searching through the framework XHR in jQuery they don't allow you to change the User-Agent or Referer headers. The closest thing:

// Set header so the called script knows that it's an XMLHttpRequest
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");

I'm leaning towards the opinion that what you want to do is being denied by a security policy in FF - if you want to pass some custom Referer type header you could always do:

xhr.setRequestHeader('X-Alt-Referer', 'http://www.google.com');

How to send an HTTP request with a header parameter?

If it says the API key is listed as a header, more than likely you need to set it in the headers option of your http request. Normally something like this :

headers: {'Authorization': '[your API key]'}

Here is an example from another Question

$http({method: 'GET', url: '[the-target-url]', headers: {
'Authorization': '[your-api-key]'}
});

Edit : Just saw you wanted to store the response in a variable. In this case I would probably just use AJAX. Something like this :

$.ajax({ 
type : "GET",
url : "[the-target-url]",
beforeSend: function(xhr){xhr.setRequestHeader('Authorization', '[your-api-key]');},
success : function(result) {
//set your variable to the result
},
error : function(result) {
//handle the error
}
});

I got this from this question and I'm at work so I can't test it at the moment but looks solid

Edit 2: Pretty sure you should be able to use this line :

headers: {'Authorization': '[your API key]'},

instead of the beforeSend line in the first edit. This may be simpler for you

Programmatically setting http request headers in javascript for Content-Type

According to MDN:

Sets the value of an HTTP request header. You must call
setRequestHeader()after open(), but before send(). If this method is
called several times with the same header, the values are merged into
one single request header.

So calling setRequestHeader() multiple times will yield the following:

Content-Type: application/x-www-form-urlencoded, application/json

Set multiple request header in javascript

request.setRequestHeader() Can be called multiple times, each time it is called it will add a new header. Therefore what you have done in your question is correct.

client.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
client.setRequestHeader('Content-Type', 'text/html');

Will cause your request to have two headers.

JavaScript - How to set request header for a browser GET

In more recent browsers, you might be able to use blobs:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button onclick="tryit();">PDF</button>
<script>
function tryit() {
var win = window.open('_blank');
downloadFile('/pdf', function(blob) {
var url = URL.createObjectURL(blob);
win.location = url;
});
}
function downloadFile(url, success) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.setRequestHeader("Authorization", "Basic " + btoa("username:password"));
xhr.responseType = "blob";
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (success) success(xhr.response);
}
};
xhr.send(null);
}

</script>
</body>
</html>

In IE, ask the user:

window.navigator.msSaveOrOpenBlob(blob, 'readme.pdf');

P.S.
You can test the backend in Node:

router.get('/pdf', function(req, res) {
if(req.headers.authorization !== 'Basic dXNlcm5hbWU6cGFzc3dvcmQ=') return res.status(403).send('Not allowed');
res.sendFile(path.join(__dirname, 'public', 'render.pdf'));
});
router.get('/', function(req, res) {
res.render('index');
});

Accessing the web page's HTTP Headers in JavaScript

Unfortunately, there isn't an API to give you the HTTP response headers for your initial page request. That was the original question posted here. It has been repeatedly asked, too, because some people would like to get the actual response headers of the original page request without issuing another one.


For AJAX Requests:

If an HTTP request is made over AJAX, it is possible to get the response headers with the getAllResponseHeaders() method. It's part of the XMLHttpRequest API. To see how this can be applied, check out the fetchSimilarHeaders() function below. Note that this is a work-around to the problem that won't be reliable for some applications.

myXMLHttpRequest.getAllResponseHeaders();
  • The API was specified in the following candidate recommendation for XMLHttpRequest: XMLHttpRequest - W3C Candidate Recommendation 3 August 2010

  • Specifically, the getAllResponseHeaders() method was specified in the following section: w3.org: XMLHttpRequest: the getallresponseheaders() method

  • The MDN documentation is good, too: developer.mozilla.org: XMLHttpRequest.

This will not give you information about the original page request's HTTP response headers, but it could be used to make educated guesses about what those headers were. More on that is described next.


Getting header values from the Initial Page Request:

This question was first asked several years ago, asking specifically about how to get at the original HTTP response headers for the current page (i.e. the same page inside of which the javascript was running). This is quite a different question than simply getting the response headers for any HTTP request. For the initial page request, the headers aren't readily available to javascript. Whether the header values you need will be reliably and sufficiently consistent if you request the same page again via AJAX will depend on your particular application.

The following are a few suggestions for getting around that problem.


1. Requests on Resources which are largely static

If the response is largely static and the headers are not expected to change much between requests, you could make an AJAX request for the same page you're currently on and assume that they're they are the same values which were part of the page's HTTP response. This could allow you to access the headers you need using the nice XMLHttpRequest API described above.

function fetchSimilarHeaders (callback) {
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (request.readyState === XMLHttpRequest.DONE) {
//
// The following headers may often be similar
// to those of the original page request...
//
if (callback && typeof callback === 'function') {
callback(request.getAllResponseHeaders());
}
}
};

//
// Re-request the same page (document.location)
// We hope to get the same or similar response headers to those which
// came with the current page, but we have no guarantee.
// Since we are only after the headers, a HEAD request may be sufficient.
//
request.open('HEAD', document.location, true);
request.send(null);
}

This approach will be problematic if you truly have to rely on the values being consistent between requests, since you can't fully guarantee that they are the same. It's going to depend on your specific application and whether you know that the value you need is something that won't be changing from one request to the next.


2. Make Inferences

There are some BOM properties (Browser Object Model) which the browser determines by looking at the headers. Some of these properties reflect HTTP headers directly (e.g. navigator.userAgent is set to the value of the HTTP User-Agent header field). By sniffing around the available properties you might be able to find what you need, or some clues to indicate what the HTTP response contained.


3. Stash them

If you control the server side, you can access any header you like as you construct the full response. Values could be passed to the client with the page, stashed in some markup or perhaps in an inlined JSON structure. If you wanted to have every HTTP request header available to your javascript, you could iterate through them on the server and send them back as hidden values in the markup. It's probably not ideal to send header values this way, but you could certainly do it for the specific value you need. This solution is arguably inefficient, too, but it would do the job if you needed it.

How can I add a custom HTTP header to ajax request with js or jQuery?

There are several solutions depending on what you need...

If you want to add a custom header (or set of headers) to an individual request then just add the headers property:

// Request with custom header
$.ajax({
url: 'foo/bar',
headers: { 'x-my-custom-header': 'some value' }
});

If you want to add a default header (or set of headers) to every request then use $.ajaxSetup():

$.ajaxSetup({
headers: { 'x-my-custom-header': 'some value' }
});

// Sends your custom header
$.ajax({ url: 'foo/bar' });

// Overwrites the default header with a new header
$.ajax({ url: 'foo/bar', headers: { 'x-some-other-header': 'some value' } });

If you want to add a header (or set of headers) to every request then use the beforeSend hook with $.ajaxSetup():

$.ajaxSetup({
beforeSend: function(xhr) {
xhr.setRequestHeader('x-my-custom-header', 'some value');
}
});

// Sends your custom header
$.ajax({ url: 'foo/bar' });

// Sends both custom headers
$.ajax({ url: 'foo/bar', headers: { 'x-some-other-header': 'some value' } });

Edit (more info): One thing to be aware of is that with ajaxSetup you can only define one set of default headers and you can only define one beforeSend. If you call ajaxSetup multiple times, only the last set of headers will be sent and only the last before-send callback will execute.



Related Topics



Leave a reply



Submit