How to pass headers for an XMLHttpRequest request

旧时模样 提交于 2021-02-17 05:23:05

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/44911095/how-to-pass-headers-for-an-xmlhttprequest-request

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!