jQuery的$就自定义HTTP标问题自定义、问题、jQuery、HTTP

2023-09-10 17:19:19 作者:我要感谢你,赠我空欢喜

我查询一个REST Web服务,它使用自定义HTTP标认证。

I'm querying a REST webservice which uses custom http headers for authentication.

如果我执行POST没有我收到了预期误差的头,但是当我添加的头,我收到了404错误,而不是我所真正需要的。

If I perform a POST without the headers I'm getting the expected error, but when I add the headers I get a 404 error instead of what I actually need.

这是我的code

$.ajax({
  type: 'POST',
  url: 'http://server.com/service',
  beforeSend: function (xhr) { xhr.setRequestHeader('CUSTOM-HEADER-KEY', 'CUSTOM-HEADER-VALUE') },
  success: function(data) {    
    alert('success.');
  }
});

这里的萤火虫头输出:

Here's the firebug headers output:

选项 /服务HTTP / 1.1   主持人:server.com   用户代理:Mozilla的/ 5.0(Windows NT的6.1; WOW64; RV:8.0.1)的Gecko / 20100101 Firefox的/ 8.0.1   接受:text / html的,是application / xhtml + xml的,应用程序/ XML; Q = 0.9, / 的; Q = 0.8   接受语言:EN-US,EN; Q = 0.5   接受编码:gzip,紧缩   接收字符集:ISO-8859-1,UTF-8,Q = 0.7,*; Q = 0.7   连接:保持活动   产地:空   访问控制请求-方法:POST   访问控制请求报头:自定义标题键   杂注:无缓存   缓存控制:无缓存

OPTIONS /service HTTP/1.1 Host: server.com User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:8.0.1) Gecko/20100101 Firefox/8.0.1 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip, deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Connection: keep-alive Origin: null Access-Control-Request-Method: POST Access-Control-Request-Headers: custom-header-key Pragma: no-cache Cache-Control: no-cache

和SMAE头表演后与海报,返回所需的结果时。

and the smae headers when performing the post with poster, which returns desired result.

发表 /服务HTTP / 1.1   主持人:server.com   用户代理:Mozilla的/ 5.0(Windows NT的6.1; WOW64; RV:8.0.1)的Gecko / 20100101 Firefox的/ 8.0.1   接受:text / html的,是application / xhtml + xml的,应用程序/ XML; Q = 0.9, / 的; Q = 0.8   接受语言:EN-US,EN; Q = 0.5   接受编码:gzip,紧缩   接收字符集:ISO-8859-1,UTF-8,Q = 0.7,*; Q = 0.7   连接:保持活动   自定义头-KEY:自定义头值   杂注:无缓存   缓存控制:无缓存   内容长度:0

POST /service HTTP/1.1 Host: server.com User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:8.0.1) Gecko/20100101 Firefox/8.0.1 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip, deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Connection: keep-alive CUSTOM-HEADER-KEY: CUSTOM-HEADER-VALUE Pragma: no-cache Cache-Control: no-cache Content-Length: 0

的区别是pretty的明显,但我不知道我在做什么错在jQuery的code。

The difference is pretty obvious, but I don't know what I'm doing wrong in the jquery code.

谁能帮帮我好吗?

推荐答案

在一个跨域请求,如果头部不被服务的浏览器允许将简单地将其删除

In a cross domain request if the header is not allowed by the service browser will simply remove it

在第一个浏览器的浏览器将选项调用,以检查允许的(产地,接头,方法)

At first browser browser will make an OPTION call to check for the allowed (Origin, Headers, Methods)

在您的服务配置,你必须允许以便在头能够使用将它发送到服务器

In your service configuration you have to allow the header in order to be able to send it to server using

Access-Control-Allow-Headers: YOUR_HEADER_NAME