我使用js
和AWS S3
管理静态文件,包括AWS CloudFront
个文件。
我有一个代码发送ajax POST
请求(我的django
视图之一),此a.js
文件位于S3
。
我意识到我遇到了一些跨域问题,因此我在https://docs.djangoproject.com/en/1.10/ref/csrf/#ajax中复制并粘贴了一些代码。这是我的js
代码:
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
$.ajax({
type: "POST",
url: '/orders/pay-check/',
data: {
imp_uid : rsp.imp_uid,
merchant_uid : rsp.merchant_uid
}, // form date가 아니기 때문에, 맨위에 ajax cookie 세팅을 해줘야함
success: function(data) {
...
}
});
但它发生csrf_token
错误!所以我详细查看了这段代码并尝试编辑代码的一部分:
第一种方式:在POST
中添加csrfSafeMethod
并移除this.crossdomain
。
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|POST|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type)) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
第二种方式:只需在POST
中添加csrfSafeMethod
:
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|POST|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
第三种方式:在POST
中添加csrfSafeMethod
并将!this.crossDomain
更改为this.crossDomain
。
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|POST|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
但所有这些情况都不起作用!! ....
真的想得到一些建议。感谢。
**编辑**
我有点奇怪。
如果我打开Chorme development tool
控制台并打印document.cookie
,其输出不包括我本地开发环境中包含的csrftoken
....仅在生产环境中不包含它出现了