我想将自定义标头添加到来自 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 观看时,我看到了以下标头:
选项 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 Accept-Language: fr,fr-fr;q=0.8,en-us;q=0.5,en;q=0.3 Accept-Encoding: gzip, deflate 连接: keep -alive 来源:null 访问控制请求方法:POST 访问控制请求标头:my-first-header,my-second-header 编译指示:无缓存 缓存控制:无缓存
为什么我的自定义标题转到 Access-Control-Request-Headers
:
访问控制请求标头:我的第一个标头,我的第二个标头
我期待这样的标题值:
My-First-Header:第一个值 My-Second-Header:第二个值
可能吗?
OPTIONS
请求(所谓的飞行前请求),用于了解远程主机是否愿意接收请求。您应该查看实际的(即 POST
)请求,看看它是否正确设置了所有标头。
这是一个如何在 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));
}
});
下面的代码对我有用。我总是只使用单引号,而且效果很好。我建议你应该只使用单引号或只使用双引号,但不要混淆。
$.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 标头包括实际请求中的标头列表。然后,在浏览器提交实际请求之前,服务器应报告此上下文中是否支持这些标头。
因为您发送自定义标头,所以您的 CORS 请求是 not a simple request,所以浏览器首先发送预检 OPTIONS 请求以检查服务器是否允许您的请求。
https://i.stack.imgur.com/BTFel.png
如果您在服务器上打开 CORS,那么您的代码将起作用。您也可以改用 JavaScript fetch (here)
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 + ' 已发送 - 打开 chrome 控制台> 网络查看它'); });
这是一个在 nginx 上打开 CORS 的示例配置(nginx.conf 文件):
location ~ ^/index\.php(/|$) { ... add_header 'Access-Control-Allow-Origin' "$http_origin" 总是; add_header 'Access-Control-Allow-Credentials' 'true' 总是; if ($request_method = OPTIONS) { add_header 'Access-Control-Allow-Origin' "$http_origin"; # 不要删除此行(与上面的外部“if”加倍) add_header 'Access-Control-Allow-Credentials' 'true'; add_header '访问控制-最大年龄' 1728000; # 缓存 20 天的预检值 add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; add_header 'Access-Control-Allow-Headers' '我的第一个标题,我的第二个标题,授权,内容类型,接受,来源'; add_header '内容长度' 0; add_header 'Content-Type' 'text/plain charset=UTF-8';返回204; } }
这是在 Apache 上打开 CORS 的示例配置(.htaccess 文件)
#------------------------------------------------ ----------------------------------------- # |跨域 Ajax 请求 | #------------------------------------------------ ----------------------------- # 启用跨域 Ajax 请求。 # http://code.google.com/p/html5security/wiki/CrossOriginRequestSecurity # http://enable-cors.org/ #
这就是为什么您不能使用 JavaScript 创建机器人的原因,因为您的选择仅限于浏览器允许您执行的操作。您不能只订购遵循大多数浏览器遵循的 CORS 政策的浏览器,将随机请求发送到其他来源并让您获得如此简单的响应!
此外,如果您尝试手动编辑某些请求标头,例如浏览器附带的开发人员工具中的 origin-header
,浏览器将拒绝您的编辑并可能发送预检 OPTIONS
请求。
尝试添加 '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);
});
从客户端,我无法解决这个问题。
在 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(),这些 OPTIONS 必须出现在 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({
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)
}
});
不定期副业成功案例分享