Add header in AJAX request with jQuery
我想从jquery向ajax post请求添加一个自定义头文件。
我尝试过:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | $.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); }); |
当我发送此请求并使用Firebug观看时,我看到此标题:
OPTIONS xxxx/yyyy HTTP/1.1
Host: 127.0.0.1:6666
User-Agent: 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
Accept-Language: fr,fr-fr;q=0.8,en-us;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Connection: keep-alive
Origin: null
Access-Control-Request-Method: POST
Access-Control-Request-Headers: my-first-header,my-second-header
Pragma: no-cache
Cache-Control: no-cache
为什么我的自定义头会转到
Access-Control-Request-Headers: my-first-header,my-second-header
我期望有这样的头值:
My-First-Header: first value
My-Second-Header: second value
有可能吗?
以下是如何在jquery ajax调用中设置请求头的示例:
1 2 3 4 5 6 7 8 9 10 11 12 | $.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)); } }); |
下面的代码适用于我。我总是只用单引号,而且它工作得很好。我建议您只使用单引号或双引号,但不要混淆。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | $.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); } }); |
希望这能回答你的问题…
您在Firefox中看到的并不是实际的请求;请注意,HTTP方法是选项,而不是POST。实际上是浏览器为确定是否允许跨域Ajax请求而发出的"飞行前"请求:
http://www.w3.org/tr/cors/
飞行前请求中的访问控制请求标题包括实际请求中的标题列表。然后,在浏览器提交实际请求之前,服务器将报告这些头是否在此上下文中受支持。
这就是为什么你不能用JavaScript创建一个机器人,因为你的选择被限制在浏览器允许你做的事情上。您不能只订购遵循大多数浏览器遵循的
此外,如果您试图从浏览器随附的开发人员工具中手动编辑一些请求头,如
因为您发送自定义头,所以CORS请求不是简单的请求,所以浏览器首先发送prefilight选项请求,以检查服务器是否允许您的请求。
如果您在服务器上打开CORS,那么您的代码将工作。您也可以使用JS FETCH(此处)
1 2 3 4 5 6 7 8 9 10 11 12 13 | let url='https://server.test-cors.org/server?enable=true&status=200&methods=POST&headers=My-First-Header,My-Second-Header'; $.ajax({ type: 'POST', url: url, headers: { "My-First-Header":"first value", "My-Second-Header":"second value" } }).done(function(data) { alert(data[0].request.httpMethod + ' was send - open chrome console> network to see it'); }); |
1 | <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"> |
下面是在nginx(nginx.conf文件)上打开cors的配置示例。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | location ~ ^/index\.php(/|$) { ... add_header 'Access-Control-Allow-Origin'"$http_origin" always; add_header 'Access-Control-Allow-Credentials' 'true' always; if ($request_method = OPTIONS) { add_header 'Access-Control-Allow-Origin'"$http_origin"; # DO NOT remove THIS LINES (doubled with outside 'if' above) add_header 'Access-Control-Allow-Credentials' 'true'; add_header 'Access-Control-Max-Age' 1728000; # cache preflight value for 20 days add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'My-First-Header,My-Second-Header,Authorization,Content-Type,Accept,Origin'; add_header 'Content-Length' 0; add_header 'Content-Type' 'text/plain charset=UTF-8'; return 204; } } |
下面是在Apache(.htaccess文件)上打开CORS的配置示例。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | # ------------------------------------------------------------------------------ # | Cross-domain AJAX requests | # ------------------------------------------------------------------------------ # Enable cross-origin AJAX requests. # http://code.google.com/p/html5security/wiki/CrossOriginRequestSecurity # http://enable-cors.org/ # <IfModule mod_headers.c> # Header set Access-Control-Allow-Origin"*" # </IfModule> #Header set Access-Control-Allow-Origin"http://example.com:3000" #Header always set Access-Control-Allow-Credentials"true" Header set Access-Control-Allow-Origin"*" Header always set Access-Control-Allow-Methods"POST, GET, OPTIONS, DELETE, PUT" Header always set Access-Control-Allow-Headers"My-First-Header,My-Second-Header,Authorization, content-type, csrf-token" |
尝试使用Rack Cors Gem。并在Ajax调用中添加头字段。