jquery $.ajax custom http headers issue

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

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.

This is my 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:

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

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

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

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

Could anyone help me please?


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

This is a Cross domain request. So you cannot solve it from browser side. You might need a Server Side Proxy to perform POST to a different domain.


这可能或不会帮助,但我认为你可以在数据选项中添加标题:

$.ajax({
  type: 'POST',
  data: put the results of your header request here,
  url: 'http://server.com/service',
  beforeSend: function (xhr) { xhr.setRequestHeader('CUSTOM-HEADER-KEY', 'CUSTOM-HEADER-VALUE') },
  success: function(data) {    
    alert('success.');
  }
});
链接地址: http://www.djcxy.com/p/46244.html

上一篇: 405角色js发布到web服务(firefox)

下一篇: jquery $ .ajax自定义http头问题