【问题标题】:Ajax Post Form across different domains apps跨不同域应用程序的 Ajax 发布表单
【发布时间】:2015-09-17 13:20:54
【问题描述】:

我有一个用 bootstrap 和 jquery 构建的静态 html 页面。上面有一个联系我们的表格,我在上面设置了对我的 django 应用程序的 Ajax Post 调用。

静态 html 页面托管在 windows 服务器上,而我的 django 应用程序托管在 heroku 上。 在 ajax 调用中,我通过 jquery 获取 csrf 令牌,但它返回 null。

 $("#submit_button").click(function() {
        var from_name           = $("#Name").val();
        var from_email          = $("#email").val();
        var story_subject       = $("#Message").val();
        var csrftoken = getCookie('csrftoken');
        console.log(from_name);
        console.log(from_email);
        console.log(story_subject);
        console.log(csrftoken);
        $.ajax({
          type: 'POST',
          url: 'http://www.example.com/users/api-26/',
          useDefaultXhrHeader: false,
          crossDomain: true, // enable this
          dataType: 'jsonp',
          data: {
          'from_name': from_name,
          'from_email':from_email,
          'story_subject':story_subject,
          'csrfmiddlewaretoken': csrftoken
          },
          beforeSend: function(xhr) {
            xhr.setRequestHeader('X-CSRFToken', $.cookie('csrftoken')),
          },
          success: function (response_data) {
            var _result = JSON.parse(response_data);
            if(_result.status == 'True'){
              $('#myModal').hide();
              console.log("sent");
            }else{
              console.log(response.error.message);
            }
          },
          error: function(xhr, textStatus, thrownError) {
            console.log(xhr.status + ": " + xhr.responseText);
          }

        });
        return false;
      });

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 = cookies[i].trim();
            // 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;
}

和 Django 视图

@csrf_protect
@require_http_methods(["POST"])
def Contactus(request):

由于我在使用 csrf 令牌时遇到问题,是否有任何其他方法可以确保此调用安全。

【问题讨论】:

  • 由于浏览器安全措施,即使使用正确的 CSRF 令牌,跨域 POST 也无法工作。要使其正常工作,您需要设置 CORS (stackoverflow.com/a/7605119/1059782)。

标签: javascript jquery ajax django csrf


【解决方案1】:

如前所述,您需要在端点上启用 CORS(跨域资源共享)才能执行 Ajax 操作或使用JSONP 进行响应,我建议这是一种更简单的方法。

要启用 CORS,您可以使用 django-cors-headers 包,其中有一些选项可供使用,例如白名单。

【讨论】:

  • console.log(csrftoken); 这在我的控制台中打印为 null。
猜你喜欢
  • 2012-02-19
  • 2012-06-05
  • 1970-01-01
  • 1970-01-01
  • 2013-03-18
  • 1970-01-01
  • 2019-01-16
  • 1970-01-01
  • 2013-11-06
相关资源
最近更新 更多