使用jQuery在AJAX请求中添加标头

本文探讨了在使用jQuery进行AJAX POST请求时如何添加自定义标头的问题。作者发现自定义标头被添加到了Access-Control-Request-Headers中,而预期是直接作为请求的一部分。其他回复解释了这是因为浏览器的跨域请求策略,即预检请求(OPTIONS),并提供了设置请求标头的示例代码。
摘要由CSDN通过智能技术生成

本文翻译自:Add header in AJAX request with jQuery

I would like to add a custom header to an AJAX POST request from jQuery. 我想向jQuery的AJAX POST请求添加自定义标头。

I have tried this: 我已经试过了:

$.ajax({
    type: 'POST',
    url: url,
    headers: {
        "My-First-Header":"first value",
        "My-Second-Header":"second value"
    }
    //OR
    //beforeSend: function(xhr) { 
    //  xhr.setRequestHeader("My-First-Header", "first value"); 
    //  xhr.setRequestHeader("My-Second-Header", "second value"); 
    //}
}).done(function(data) { 
    alert(data);
});

When I send this request and I watch with FireBug, I see this header: 当我发送此请求并观看FireBug时,看到以下标头:

OPTIONS xxxx/yyyy HTTP/1.1 选项xxxx / yyyy HTTP / 1.1
Host: 127.0.0.1:6666 主持人:127.0.0.1:6666
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:11.0) Gecko/20100101 Firefox/11.0 用户代理:Mozilla / 5.0(Windows NT 6.1; WOW64; rv:11.0)Gecko / 20100101 Firefox / 11.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9, / ;q=0.8 接受:text / html,application / xhtml + xml,application / xml; q = 0.9, / ; q = 0.8
Accept-Language: fr,fr-fr;q=0.8,en-us;q=0.5,en;q=0.3 接受语言:fr,fr-fr; q = 0.8,en-us; q = 0.5,en; q = 0.3
Accept-Encoding: gzip, deflate 接受编码:gzip,放气
Connection: keep-alive 连接:保持活动状态
Origin: null 来源:null
Access-Control-Request-Method: POST 访问控制请求方法:POST
Access-Control-Request-Headers: my-first-header,my-second-header 访问控制请求标头:我的第一标头,我的第二标头
Pragma: no-cache 语法:无缓存
Cache-Control: no-cache 缓存控制:无缓存

Why do my custom headers go to Access-Control-Request-Headers : 为什么我的自定义标头转到Access-Control-Request-Headers

Access-Control-Request-Headers: my-first-header,my-second-header 访问控制请求标头:我的第一标头,我的第二标头

I was expecting a header values like this: 我期待这样的标头值:

My-First-Header: first value My-First-Header:第一个值
My-Second-Header: second value 我的第二标题:第二个值

Is it possible? 可能吗?


#1楼

参考:https://stackoom.com/question/gLfB/使用jQuery在AJAX请求中添加标头


#2楼

What you saw in Firefox was not the actual request; 您在Firefox中看到的不是实际的请求; note that the HTTP method is OPTIONS, not POST. 请注意,HTTP方法是OPTIONS,而不是POST。 It was actually the 'pre-flight' request that the browser makes to determine whether a cross-domain AJAX request should be allowed: 实际上,这是浏览器发出的“飞行前”请求,以确定是否应允许跨域AJAX请求:

http://www.w3.org/TR/cors/ http://www.w3.org/TR/cors/

The Access-Control-Request-Headers header in the pre-flight request includes the list of headers in the actual request. 飞行前请求中的Access-Control-Request-Headers标头包括实际请求中的标头列表。 The server is then expected to report back whether these headers are supported in this context or not, before the browser submits the actual request. 然后,在浏览器提交实际请求之前,服务器将在此上下文中报告是否支持这些标头。


#3楼

Here is an example how to set a Request Header in a JQuery Ajax Call: 这是一个如何在JQuery Ajax调用中设置请求标头的示例:

$.ajax({
  type: "POST",
  beforeSend: function(request) {
    request.setRequestHeader("Authority", authorizationToken);
  },
  url: "entities",
  data: "json=" + escape(JSON.stringify(createRequestObject)),
  processData: false,
  success: function(msg) {
    $("#results").append("The result =" + StringifyPretty(msg));
  }
});

#4楼

This code below works for me. 下面的代码对我有用。 I always use only single quotes, and it works fine. 我总是只使用单引号,并且效果很好。 I suggest you should use only single quotes OR only double quotes, but not mixed up. 我建议您仅使用单引号或仅使用双引号,但不要混用。

$.ajax({
    url: 'YourRestEndPoint',
    headers: {
        'Authorization':'Basic xxxxxxxxxxxxx',
        'X-CSRF-TOKEN':'xxxxxxxxxxxxxxxxxxxx',
        'Content-Type':'application/json'
    },
    method: 'POST',
    dataType: 'json',
    data: YourData,
    success: function(data){
      console.log('succes: '+data);
    }
  });

Hope this answers your question... 希望这能回答您的问题...


#5楼

And that is why you can't create a bot with Javascript, because your options are limited to what the browser allows you to do. 这就是为什么您不能使用Javascript创建机器人的原因,因为您的选择仅限于浏览器允许执行的操作。 You can't just order a browser that follows the CORS policy, which most browsers follow, to send random requests to other origins and allow you to get the response that simply! 您不能仅订购遵循大多数浏览器遵循的CORS策略的浏览器, CORS随机请求发送到其他来源,并让您获得简单的响应!

Additionally, if you tried to edit some request headers manually like origin-header from the developers tools that come with the browsers, the browser will refuse your edit, and may send a preflight OPTIONS request. 此外,如果您尝试手动编辑一些请求标头,例如来自浏览器随附的开发人员工具中的origin-header ,则浏览器将拒绝您的编辑,并可能发送预检OPTIONS请求。


#6楼

Try to use rack-cors gem. 尝试使用齿条心形宝石。 And add the header field in your ajax call. 并在您的ajax调用中添加标头字段。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值