![](/img/trans.png)
[英]jquery ajax post request Access-Control-Request-Headers
[英]Access Control Request Headers, is added to header in AJAX request with jQuery
我想將自定義 header 添加到來自 jQuery 的 AJAX POST 請求。
我試過這個:
$.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 觀看時,我看到了這個 header:
選項 xxxx/yyyy HTTP/1.1
主機:127.0.0.1:6666
用戶代理:Mozilla/5.0 (Windows NT 6.1; WOW64; rv:11.0) Gecko/20100101 Firefox/11.0
接受:text/html,application/xhtml+xml,application / xml;q=0.9, /;q=0.8
接受語言:fr,fr-fr;q=0.8,en-us;q=0.5,en;q=0.3
接受編碼:gzip、deflate
連接:保持活動狀態
產地:null
訪問控制請求方法:POST
訪問控制請求標頭:我的第一個標頭,我的第二個標頭
Pragma:無緩存
緩存控制:無緩存
為什么我的自定義標頭 go 到Access-Control-Request-Headers
:
訪問控制請求標頭:我的第一個標頭,我的第二個標頭
我期待這樣的 header 值:
My-First-Header:第一個值
My-Second-Header:第二個值
可能嗎?
以下是如何在 jQuery Ajax 調用中設置請求 header 的示例:
$.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));
}
});
下面的代碼對我有用。 我總是只使用單引號,而且效果很好。 我建議你應該只使用單引號或只使用雙引號,但不要混淆。
$.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 方法是 OPTIONS,而不是 POST。 它實際上是瀏覽器發出的“飛行前”請求,以確定是否應允許跨域 AJAX 請求:
飛行前請求中的 Access-Control-Request-Headers header 包括實際請求中的標頭列表。 然后,在瀏覽器提交實際請求之前,服務器應報告此上下文是否支持這些標頭。
因為你發送自定義標頭所以你的 CORS 請求不是一個簡單的請求,所以瀏覽器首先發送一個預檢 OPTIONS 請求來檢查服務器是否允許你的請求。
如果您在服務器上打開 CORS,那么您的代碼將起作用。 您也可以改用 JavaScript fetch( 此處)
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'); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
這是一個示例配置,它在 nginx (nginx.conf 文件)上打開 CORS:
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
# ------------------------------------------------------------------------------ # | 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"
這就是為什么您不能使用 JavaScript 創建機器人的原因,因為您的選項僅限於瀏覽器允許您執行的操作。 您不能只訂購遵循大多數瀏覽器遵循的CORS策略的瀏覽器,以向其他來源發送隨機請求並允許您簡單地獲得響應!
此外,如果您嘗試手動編輯某些請求標頭,例如來自瀏覽器附帶的開發人員工具的origin-header
,瀏覽器將拒絕您的編輯並可能發送預檢OPTIONS
請求。
從客戶端來說,我無法解決這個問題。
從Node.js和Express.js端,您可以使用cors模塊來處理它。
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var cors = require('cors');
var port = 3000;
var ip = '127.0.0.1';
app.use('*/myapi',
cors(), // With this row OPTIONS has handled
bodyParser.text({type: 'text/*'}),
function(req, res, next) {
console.log('\n.----------------' + req.method + '------------------------');
console.log('| prot:' + req.protocol);
console.log('| host:' + req.get('host'));
console.log('| URL:' + req.originalUrl);
console.log('| body:', req.body);
//console.log('| req:', req);
console.log('.----------------' + req.method + '------------------------');
next();
});
app.listen(port, ip, function() {
console.log('Listening to port: ' + port);
});
console.log(('dir:' + __dirname));
console.log('The server is up and running at http://' + ip + ':' + port + '/');
如果沒有 cors(),這些選項必須出現在 POST 之前。
.----------------OPTIONS------------------------
| prot:http
| host:localhost:3000
| url:/myapi
| body: {}
.----------------OPTIONS------------------------
.----------------POST------------------------
| prot:http
| host:localhost:3000
| url:/myapi
| body: <SOAP-ENV:Envelope .. P-ENV:Envelope>
.----------------POST------------------------
Ajax 來電:
$.ajax({
type: 'POST',
contentType: "text/xml; charset=utf-8",
//These does not work
//beforeSend: function(request) {
// request.setRequestHeader('Content-Type', 'text/xml; charset=utf-8');
// request.setRequestHeader('Accept', 'application/vnd.realtime247.sct-giro-v1+cms');
// request.setRequestHeader('Access-Control-Allow-Origin', '*');
// request.setRequestHeader('Access-Control-Allow-Methods', 'POST, GET');
// request.setRequestHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type');
//},
//headers: {
// 'Content-Type': 'text/xml; charset=utf-8',
// 'Accept': 'application/vnd.realtime247.sct-giro-v1+cms',
// 'Access-Control-Allow-Origin': '*',
// 'Access-Control-Allow-Methods': 'POST, GET',
// 'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type'
//},
url: 'http://localhost:3000/myapi',
data: '<SOAP-ENV:Envelope .. P-ENV:Envelope>',
success: function(data) {
console.log(data.documentElement.innerHTML);
},
error: function(jqXHR, textStatus, err) {
console.log(jqXHR, '\n', textStatus, '\n', err)
}
});
嘗試添加'Content-Type':'application/json'
:
$.ajax({
type: 'POST',
url: url,
headers: {
'Content-Type':'application/json'
}
//OR
//beforeSend: function(xhr) {
// xhr.setRequestHeader("My-First-Header", "first value");
// xhr.setRequestHeader("My-Second-Header", "second value");
//}
}).done(function(data) {
alert(data);
});
嘗試使用rack-cors gem。 並在您的 Ajax 調用中添加 header 字段。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.