如何传递XMLHttpRequest请求的标头

编程入门 行业动态 更新时间:2024-10-27 08:28:40
本文介绍了如何传递XMLHttpRequest请求的标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个api,只需传递几个标头即可获得响应.下面是工作中的邮递员

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

现在Iam正在进行http调用以使用此代码,下面是Iam使用的代码

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

var jobendpoint = '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 }

但是当我尝试它不起作用时,我可以看到标题没有正确传递.我们如何将这些标题传递给此GET调用?有人可以帮忙吗?

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 .

更新错误******由于我的标题设置不正确,因此我收到403禁止错误.以下是在firefox的``网络''选项卡中传递的标题的屏幕截图

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

我已经直接在Firefox的n/w选项卡中编辑了标题,并发送了呼叫,并且可以正常工作.下面是屏幕截图

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

推荐答案

XMLHttpRequest.setRequestHeader() 状态:

对于您的自定义字段,当您向跨域发送请求时,可能会遇到飞行前响应中的Access-Control-Allow-Headers不允许的"异常.在这种情况下,您需要设置"服务器端响应标头中的Access-Control-Allow-Headers ".

在您的情况下, X-Rundeck-Auth-Token 标头就是这样的自定义标头,因此该标头必须列在 Access-Control-Allow-Headers 服务器的响应标头,否则您将收到上述错误,请求将失败.

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 是列入白名单的标头,可以设置时未在 Access-Control-Allow-Headers 标头中指定它们;还有一个请求标头列表,即使设置也无法设置如果它们被列出.

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.

更多推荐

如何传递XMLHttpRequest请求的标头

本文发布于:2023-10-11 04:37:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1480704.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:XMLHttpRequest

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!