I am trying to connect django and Vue API to login. I am using JWT with simple jwt and djoser library, and I have already created user.
As you can see the postman, it works fine. Does anyone know how to fix this error??
However, I cannot connect from index.html (ajax)
This is the ajax.
....
var app = new Vue({
el: '#app',
data: {
email: '',
password: ''
},
mounted: function() {},
methods: {
login(){
if (this.email == ''||this.password == '') {
alert("Email or password cannot be empty");
location. reload();
}
var data_l = {};
data_l.email = this.email;
data_l.password = this.password;
var formData = JSON.stringify(data_l);
console.log(formData);
$.ajax({
url: "http://localhost:8000/api/auth/jwt/create/",
type: "post",
dataType: "json",
data: formData,
contentType: "application/json",
success: function(rs) {
console.log(rs);
if (rs.code == "0") {
console.log(rs);
alert("Login successful!");
window.location.href = "";
} else {
alert(rs.msg);
}
},
error: function() {}
});
},
jump_to_signup() {
window.location.href = "signup.html";
},
jump_to_Fpwd(){
window.location.href = "forgotpassword.html";
}
}
})
</script>
</body>
</html>
This is settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'corsheaders',
'djoser',
'fitness_app',
'user',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'fitness.urls'
CORS_ORIGIN_ALLOW_ALL = True
CodePudding user response:
You're missing some lines in your middleware list. Replace it like this in your settings.py
file:
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
Also, I think that you are using the old attribute by using CORS_ORIGIN_ALLOW_ALL
. Use this instead:
CORS_ALLOW_ALL_ORIGINS = True
If you have any questions ask, and remember, the documentation is right here: https://github.com/adamchainz/django-cors-headers