Question just like the title.
In command line, we can type:
curl -H "header_name: header_value" "http://example"
to navigate to http://example with a custom request header as shown above.
Q: If I need to write a JavaScript to do the same thing, how should I do?
var url = 'https://example';
var myRequest = new XMLHttpRequest();
myRequest.open('GET', url ,false);
myRequest.setRequestHeader('header-name','header-value');
myRequest.send();
I tried this code, there is no syntax error but the page didn't change. Hence, I don't really know if I modified the request header(s).
 informatik01
 
 16.5k11 gold badges82 silver badges112 bronze badges
 
 
 asked Mar 15, 2016 at 14:51
 
 
 
 Marvin Choi 
 
 711 gold badge1 silver badge3 bronze badges
 
 1 Answer 1
Here is how you can handle this:
var req = new XMLHttpRequest();
req.open('GET', 'http://example', true); //true means request will be async
req.onreadystatechange = function (aEvt) {
 if (req.readyState == 4) {
 if(req.status == 200)
 //update your page here
 //req.responseText - is your result html or whatever you send as a response
 else
 alert("Error loading page\n");
 }
};
req.setRequestHeader('header_name', 'header_value');
req.send();
 answered Mar 15, 2016 at 15:19
 
 
 
 Vitaly Kulikov 
 
 7333 silver badges13 bronze badges
 
 
 Sign up to request clarification or add additional context in comments.
 
 
 
 7 Comments
Marvin Choi
 Thanks a lot, it helps me understand the use of XMLHttpRequest(). One more question, does it support adding a costumed requestheader? e.g. request header "x-api-key" which is normally appeared in every request header.
  Vitaly Kulikov
 Yes, there is example in my answer 
  req.setRequestHeader('header_name', 'header_value');Marvin Choi
 I've tried your code using 
  window.location.href = url; to update my page. The website is navigated to url however the request header doesn't apply. Am I using a wrong way to update the page?Vitaly Kulikov
 When you call req.send(); request is sent with appropriate header. When you call window.location.href = url; another request is sent. You need to update your page inside this statement if(req.status == 200) with simple DOM change. As soon as you use this approach, your site starts to be a single page application.
  Marvin Choi
 Thank you so much for clear explanation. As you mentioned 
  req.responseText saves all message I got from the GET method from my url, I've tried document.write(req.responseText) . And the page update as my desired. | 
 Explore related questions
See similar questions with these tags.
lang-js
 
 
 
window.open(url)at the end and nothing happend