Skip to content Skip to sidebar Skip to footer

How To Add Custom Header In Ajax Request Using Plain Javascript (not Jquery)?

Please could someone advise on how to add a header to an AJAX request using plain javascript? I am trying to upload a video file to a server and want to let it know the file size

Solution 1:

You can use setRequestHeader method of XMLHttpRequest:

var xmlhttp = new XMLHttpRequest();

xmlhttp.setRequestHeader('Content-Type', 'video/mp4');
xmlhttp.setRequestHeader('Content-Length', '339108')

Solution 2:

You must call it after calling open(), but before calling send()

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.open('GET', url, true);
xhr.setRequestHeader('accept', 'application/json, text/plain, */*');

And not all headers canbe set, refer this Forbidden_header_name

Tip: Server side should Also support Cross-Origin Resource Sharing (CORS), like Access-Control-Allow-Origin

Post a Comment for "How To Add Custom Header In Ajax Request Using Plain Javascript (not Jquery)?"