python - Django/AngularJS : CSFR Token Error

标签 python angularjs django cookies csrf

我对 Django 和 AngularJS 都很陌生,我已经为此苦苦挣扎了几个小时。

(我的 Controller 的)AngularJS 代码 POST 到 Django 服务器:

$http({
    method: 'POST',
    url: 'http://127.0.0.1:8000/polls/', // This is the Django server IP
    data: {'string': 'body'}
    }).then(function successCallback(response) {
     $scope.var= "success";
  }, function errorCallback(response) {
    $scope.var= response; // To display error. 
     });

    }
})

Django 服务器代码(查看):

def index(request):
    return "true"

我收到的确切错误是: 发布http://127.0.0.1:8000/polls/ 403(禁止)

错误详细信息 - CSRF 验证失败。请求已中止。您看到此消息是因为此站点在提交表单时需要 CSRF cookie。出于安全原因需要此 cookie,以确保您的浏览器不会被第三方劫持。巴拉巴拉。

编辑 更喜欢在不影响 Django 任何安全规定的情况下工作的解决方案

最佳答案

您必须在调用后的 header 中包含 token csrf

    var csrf ='{{ csrf_token }}';
    $http({
        method: 'POST',
        headers: {'X-CSRFToken' : csrf },
        url: 'http://127.0.0.1:8000/polls/', // This is the Django server IP
        data: {'string': 'body'}
        }).then(function successCallback(response) {
         $scope.var= "success";
      }, function errorCallback(response) {
        $scope.var= response; // To display error. 
         });

        }
    })

或免除本次调用的 csrf token

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def index(request):
    return "true"

关于python - Django/AngularJS : CSFR Token Error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44590127/

相关文章:

javascript - 当输入 ng-model 是 ngRepeat 变量时如何从输入数据中获取?

javascript - 带参数的自定义验证

python - 何时以及为何使用 Django 开发服务器?

django - Nginx 403 禁止提供大图像

python - 可编程透明转发代理

python - 在旧版本的 Python 上使用通过 ParamSpec 键入的 Python 代码

python - 如何在 Python 超过 10,000 行的文件中计算每个系统的系外行星?

c# - 在 CMD 中运行脚本可以工作,但是在 C# python 脚本中使用 Process.Start() 运行时失败

javascript - 为什么使用 $route (AngularJS) 更改时带有此流程图的 div 无法正确调整大小

html - 如何用django方式更改每个页面的背景图片和内容