我有分别运行的Django和angularjs应用。我可以使用angularjs登录到系统。但是在登录request.django之后,user会提供空数据。
MIDDLEWARE_CLASSES = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
登录代码:
@csrf_exempt
def login_for_new_design(request, *args, **kwargs):
if request.method == "POST":
temp=json.loads(request.body)
username = temp.get("username", None)
password = temp.get("password", None)
user = authenticate(username=username, password=password)
response_data = {}
if user:
login(request, user)
response_data['success'] = True
response_data['message'] = 'Login was succesfull!'
else: # invalid case
response_data['success'] = True
response_data['message'] = 'Login was Failure!'
response = HttpResponse(json.dumps(response_data));
response["Access-Control-Allow-Origin"] = "*"
response["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS"
response["Access-Control-Max-Age"] = "1000"
response["Access-Control-Allow-Headers"] = "*"
return response
ajax方法:
$http({
method:'POST',
url:uri,
datatype:"json",
data:payload,
headers: {
'Content-Type': undefined
},
}).then(function(result){
console.log(result)
localStorage.setItem("username", $scope.username);
$state.go('app.main', {showLeftnav: true});
},function(error){
console.log(error)
})
以上两种方法都可以正常工作。 但是当我要使用以下方法测试用户是否登录时,
@csrf_exempt
def isAuthenticated_user(request):
userdic = {};
userdic['username'] = request.user.username
print userdic
response = HttpResponse(json.dumps(userdic));
response["Access-Control-Allow-Origin"] = "*"
response["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS"
response["Access-Control-Max-Age"] = "1000"
response["Access-Control-Allow-Headers"] = "*"
return response
var csrftoken = $cookies.get('csrftoken')
authPromise = $http({
'method': "POST",
'url': "http://localhost:8000/isAuthenticated_user/",
headers:{
"X-CSRFToken": csrftoken,
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
// 'withCredentials':true
},
})
request.user提供空数据。
请让我知道我做错了什么地方。
答案 0 :(得分:0)
尝试
user = self.request.query_params.get('username',None)
print user
让我知道是否发生了一些错误