Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Navigate to URL with custom request headers in JavaScript

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

like image 330
Marvin Choi Avatar asked Oct 31 '22 07:10

Marvin Choi


1 Answers

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();
like image 154
Vitaly Kulikov Avatar answered Nov 14 '22 22:11

Vitaly Kulikov