Asked  7 Months ago    Answers:  5   Viewed   83 times

Does anyone know how to add or create a custom HTTP header using JavaScript or jQuery?

 Answers

41

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.

Tuesday, June 1, 2021
 
cbcp
answered 7 Months ago
44

Use:

response.headers['HEADER NAME'] = 'HEADER VALUE'

either in a specific method or to a before_filter method of your application controller depending on whether you need this to be added in a specific or to all of your responses.

UPDATE for Rails 5 - February 24th, 2018

As noted by @BrentMatzelle in the comments, for Rails 5:

response.set_header('HEADER NAME', 'HEADER VALUE')
Tuesday, July 13, 2021
 
TheTechnicalPaladin
answered 5 Months ago
82

I have provided an example scenario to help get you started:

<!-- Include this jQuery library in your HTML somewhere: -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script

This is probably best to include inside of an external JS file:

//Listen when a button, with a class of "myButton", is clicked
//You can use any jQuery/JavaScript event that you'd like to trigger the call
$('.myButton').click(function() {
//Send the AJAX call to the server
  $.ajax({
  //The URL to process the request
    'url' : 'page.php',
  //The type of request, also known as the "method" in HTML forms
  //Can be 'GET' or 'POST'
    'type' : 'GET',
  //Any post-data/get-data parameters
  //This is optional
    'data' : {
      'paramater1' : 'value',
      'parameter2' : 'another value'
    },
  //The response from the server
    'success' : function(data) {
    //You can use any jQuery/JavaScript here!!!
      if (data == "success") {
        alert('request sent!');
      }
    }
  });
});
Monday, August 9, 2021
 
Taptronic
answered 4 Months ago
72

This Helped :

var req = new XMLHttpRequest();
req.open('GET', document.location, false);
req.send(null);
var headers = req.getAllResponseHeaders().toLowerCase();
alert(headers);

Accessing the web page's HTTP Headers in JavaScript

Monday, August 16, 2021
 
RobG
answered 4 Months ago
82

OutgoingResponse.StatusCode is where you'd set the status code, but it's an HttpStatusCode enum, not an integer value.

You could cast a custom value int to HttpStatusCode, but I'm not sure what the framework would do with it; most likely it would throw, but it can't hurt to try.

Although the HTTP spec doesn't disallow custom response codes, it's probably not a good idea to go that route unless you must. Perhaps a custom response header would be better?

If you must go the custom status code route, another option might be to use ASP.NET compatibility mode. That would allow you to use HttpContext.Current.Response.StatusCode, which is an int. You'd have to be hosted in IIS for this to work, however, and I don't know your architecture.

Thursday, August 26, 2021
 
Prasanna
answered 4 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :  
Share