I'm working on a vuejs and django rest single page application. the problem is so clear, that I'm getting the Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource error.
My vuex code be like:
mutations:{
addTask: function(){
axios({
url: 'http://127.0.0.1:8000/api/task-list/',
method: 'POST',
headers: {
'X-CSRFToken': getCookie('csrftoken')
}
}).then(response => {
console.log(response.data);
}).catch(err => {
console.log(err.response);
})
}
},
and my django rest urls.py, in my django application urls:
urlpatterns = [
path('task-list/', TaskList.as_view()),
path('task-create/', TaskCreate.as_view())
]
and my main app urls:
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('task.urls')),
path('api/', include('authentication.urls')),
path('home/', returnHome)
]
my views.py code:
class TaskList(APIView):
def get(self, request):
tasks = Task.objects.all()
serialized = TaskSerializer(tasks, many=True)
return Response(serialized.data, status=200)
my vue app is running on http://localhost:8080, so I installed django cors headers, configured it like the below code:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# rest api
'rest_framework',
'rest_framework.authtoken',
'corsheaders',
# my apps
'authentication',
'task'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
CORS_ALLOWED_ORIGINS = [
'http://localhost:8080',
'https://localhost:8080'
]
Although, I'm still getting the Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:8000/api/task-list/. (Reason: CORS request did not succeed)
Error!
I even tried CORS_ALLOW_ALL_ORIGINS = True
, but there are still no changes...
Is there something I'm doing wrong here? I searched a lot about this, but everywhere the solution was about to write the correct configuration for corsheaders.