最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

security - Navigate to URL with custom request headers in JavaScript - Stack Overflow

programmeradmin0浏览0评论

Question just like the title.

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

Question just like the title.

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

Share Improve this question edited May 9, 2020 at 10:41 informatik01 16.5k11 gold badges79 silver badges108 bronze badges asked Mar 15, 2016 at 14:51 Marvin ChoiMarvin Choi 711 gold badge1 silver badge3 bronze badges 4
  • There are lots of answers already on that question stackoverflow./questions/1268673/… – Vitaly Kulikov Commented Mar 15, 2016 at 14:53
  • @VitalyKulikov Thx for ment, I did some research before I post the question but seems they doesn't help. The answers in your link cant help. I shared my code in the question, hope it help. – Marvin Choi Commented Mar 15, 2016 at 14:58
  • You made a request, but you did nothing with response, that why page didn't change – Vitaly Kulikov Commented Mar 15, 2016 at 15:05
  • @VitalyKulikov Oh, I got your point. Actually, but I am pretty new to Javascript. I tried put window.open(url) at the end and nothing happend – Marvin Choi Commented Mar 15, 2016 at 15:15
Add a ment  | 

1 Answer 1

Reset to default 3

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();

发布评论

评论列表(0)

  1. 暂无评论