Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

vue.js - 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

question from:https://stackoverflow.com/questions/65896400/axios-shows-cors-error-with-django-rest-framework

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...