简体   繁体   中英

Getting “status 400 Bad Request” in django rest framework with react

I am trying to record and upload an audio to django server using rest framework. My audio is getting recorded as well as the server is working fine. But they aren't working together. I am getting a status 400 Bad request. I have tried using both axios and fetch() in react but nothing is helpful. This is when I use axios: 在此处输入图像描述

This is when I use fetch() 在此处输入图像描述

This is react code:

  onStop(recordedBlob) {
    var headers ={
      'Content-Type' : 'multipart/form-data'
    }
    const data = new FormData(); 
        data.append('audio', recordedBlob);
        console.warn(recordedBlob);
  /*      fetch("http://127.0.0.1:8000/temp/",{
          method:'POST',
          body:data,
          headers:headers
        }).then( res => console.log(res)).catch(error => {
          console.log(error);
        })*/

        axios.post("http://127.0.0.1:8000/temp/", data, { 'headers':headers
        })
        .then(res => {
            console.warn(res);
        }).catch((error)=>{
          console.log(error);
        });
        
  }

My django views file:


class AudioCreateView(ModelViewSet):
    queryset=Audio.objects.all()
    serializer_class = AudioSerializer
    def create(self, request, *args, **kwargs):
        if 'file' not in request.data:
            raise ParseError('No File Uploaded')
        file_obj = request.data['audio']
        # do some stuff with uploaded file
        Audio.objects.create(audio=file_obj)
        return Response(data="File Received")

My serializers file:



class AudioSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model= Audio
        fields = ['audio']

My django settings:



INSTALLED_APPS = [
    'corsheaders',
    'lang_translator.apps.LangTranslatorConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework'
]

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    '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',
]

MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL= "/media/"
REST_FRAMEWORK={
    'DEFAULT_PERMISSION_CLASSES': [
   'rest_framework.permissions.AllowAny',
]
}
CORS_ORIGIN_ALLOW_ALL=True

My django Model:

from django.db import models

class Audio(models.Model):
    audio = models.FileField(upload_to='images/')
    

I finally found out the problem. The problem is with the audio blob recorded. When I tried to upload audio and image files using new html file and postman. The server worked perfectly fine in both of those situations. I just need to find another way to record and send audio with react. Does anyone have any idea for this?

ModelViewset don t have 'post' action try to follow the documentation on Viewsets https://www.django-rest-framework.org/api-guide/viewsets/

'The actions provided by the ModelViewSet class are .list(), .retrieve(), .create(), .update(), .partial_update(), and .destroy().'

I finally found out the problem. The problem is with the audio blob recorded. Rather than sending the recordedBlob You should send recordedBlob.blob .Because react-mic returns a blob containing the audio blob as well as other data related to it. So recordedBlob.blob is the actual data which is to be sent.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM