简体   繁体   中英

How to pass headers for an XMLHttpRequest request

I have an api which requires few headers to passed to get the response.Below is the working postman

在此处输入图片说明

Now Iam doing an http call to consume this and below is the code Iam using

 var jobendpoint = 'http://rundeck:4440/api/14/project/Demo/jobs';
 var http = new XMLHttpRequest();
 http.open('GET',jobendpoint,false);
    http.setRequestHeader('Accept','application/json');
    http.setRequestHeader('Content-type','application/json');
    http.setRequestHeader('X-Rundeck-Auth-Token','XgTeIxQLUiv3lOSl8cXNkt4bxIGFjbzl');
 http.send();
  var joblist = http.responseText;
  http.onreadystatechange = function() {//Call a function when the state changes.
        if(http.readyState === XMLHttpRequest.DONE && http.status == 200) {
        joblist = http.responseText;
         }
        }
        return joblist
}

But when I try this it is not working.I can see that headers are not properly passed.How can we pass those headers to this GET call.can someone help .

Updating error****** Im getting 403 forbiddden error since my headers are not properly set.Below is the screen shot of headers passed in network tab of firefox 在此处输入图片说明

Ive edited the headers directly in firefox n/w tab and sent the call and it worked.Below is the screen shot

在此处输入图片说明

How can I add the headers the way I had in second screen shot

The MDN page for XMLHttpRequest.setRequestHeader() states:

For your custom fields, you may encounter "not allowed by Access-Control-Allow-Headers in preflight response" exception when you send request to cross domain. In this situation, you need set " Access-Control-Allow-Headers " in your response header at server side.

In your case, the X-Rundeck-Auth-Token header is such a custom header, and therefore this header must be listed in the Access-Control-Allow-Headers response header from the server, otherwise you'll get an error as above and the request will fail.

Accept , Accept-Language , Content-Type , Content-Length are whitelisted headers that can be set without specifying them in the Access-Control-Allow-Headers header; there's also a list of request headers that can never be set, even if they are listed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM