barryjs
barryjs

Reputation: 43

axios shows CORS error, with django rest framework

Thanks for reading. I am working with vuejs SPA with flask and django backends. Yes there are 2 backends. The application is in transition. I am switching the back end from Flask to Django Rest Framework. Some parts are still with Flask.

Problem axios POST request does not hit django server. The error in console shows as a CORS error. Same calls worked with flask-restful and flask-CORS.

GET request works fine with Django

Relevant code

BACKEND

settings.py

...
INSTALLED_APPS = [
   ...
    'rest_framework',
    'corsheaders'
   ...
]
MIDDLEWARE = [
    ...
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    ...
]

CORS_ORIGIN_ALLOW_ALL=True
...

views.py

...
class SnippetView(ListCreateView):
  queryset = Snippet.objects.all()
  serializer_class = SnippetSerializer

urls.py

...
  path('snippets/', SnippetListView.as_view(), name='snippet-list')
...

FRONTEND Vuejs

component

<template>
  <v-form
    ref="form"
    v-model="valid"
  >
    <v-text-field
      v-model="code"
      label="Code"
    ></v-text-field>

    <v-text-field
      v-model="text"
      label="text"
    ></v-text-field>
  </v-form>
</template>

axios

  ...
  let snippet = { code: 'abc', text: ''} // comes from vuetifyjs form
  axios.post('http://localhost:8000/data/snippets', snippet)
    .then(res => console.log(res.data) // not working
  ...

Adding json data works normally in django-admin dashboard, django_rest_framework API interface and in httpie command line client

So it appears the issue is with axios.

I have tried

headers: {
   'Content-Type': 'application/json',
   'Access-Control-Allow-Origin' : '*',
   'Content-Type': 'application/x-www-form-urlencoded'
}

Above have been tried separately

I have also tried with fetch, which registers the post request with server but does not return a response

I still gets cors error. The request does not even reach the server.

I have also tried different CORS settings, whitelists as mentioned here https://github.com/adamchainz/django-cors-headers

Upvotes: 0

Views: 737

Answers (1)

barryjs
barryjs

Reputation: 43

Solved! This was due to some issue with axios I updated axios to 0.21.x in vue cli and it started working

Upvotes: 1

Related Questions