1

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.

NavidMnzh
  • 169
  • 3
  • 17
  • You have two items in CORS_ALLOWED_ORIGINS List. You didn't add comma to separate them. Is it typo? Or try to edit that. – Milon Mahato May 08 '21 at 14:53
  • @MilonMahato Thanks I edited that. well I tried both of them separately and also together, but I'm still getting the error. – NavidMnzh May 08 '21 at 16:39

1 Answers1

1

You problem is the placement of the Django middleware, especially relatively to CommonMiddleware. It should be listed higher than it.

From django-cors-headers README:

CorsMiddleware should be placed as high as possible, especially before any middleware that can generate responses such as Django's CommonMiddleware or Whitenoise's WhiteNoiseMiddleware. If it is not before, it will not be able to add the CORS headers to these responses. Also if you are using CORS_REPLACE_HTTPS_REFERER it should be placed before Django's CsrfViewMiddleware (see more below).

Anas Tiour
  • 1,344
  • 3
  • 17
  • 33