简体   繁体   中英

POST 400: Bad request - Using Django REST API and React

I'm pretty new to web development so please forgive me in advance for my ignorance.

I'm using React to try to post data to server endpoint managed by Django using this method:

sendData(data) {
  const url = "http://127.0.0.1:8080/api/filtros/1/";
  const requestOptions = {
    method: "POST",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json"
    },
    body: JSON.stringify(data)
  };
  fetch(url, requestOptions);
}

On the onClick of a NavDropdown React component:

<NavDropdown.Item
  key={item.id}
  onClick={() =>
    this.sendData({
      id: 0,
      dimension_id: dimension.id,
      item_id: item.id,
      usuario_id: 1
    })
  }
>
  {item.descripcion}
</NavDropdown.Item>

This is how I register the url on the router using Django:

router.register('api/filtros/1', FiltroUsuariosViewSet, 'filtro')

My Django ModelViewSet looks like this:

class FiltroUsuariosViewSet(viewsets.ModelViewSet):

    queryset = FiltroUsuarios.objects.all()
    permission_classes = [
        permissions.AllowAny
    ]
    serializer_class = FiltroUsuariosSerializers

And my Django Serializer looks like this:

class FiltroUsuariosSerializers (serializers.ModelSerializer):
    class Meta:
        model = FiltroUsuarios
        fields = ('id', 'dimension_id', 'item_id', 'usuario_id')

    def create(self, validated_data):
        post = FiltroUsuarios.objects.create(**validated_data)

When I click on the Component I get this: POST http://127.0.0.1:8080/api/filtros/1/ 400 (Bad Request) and apparently the error is on the fetch request.

Do you guys have any idea on whats the problem?

Thanks a lot in advance!

The best way to understand and get rid of 400 Bad Request errors when wiring Django and React, is to run Django in development mode and then fire up your browser's Network tab while sending the request.

Switch into the Network -> Response tab and call sendData() . Since you are running on Django's development server, you will get the specific exception on your 400 Bad Request error. To simulate this, see the screenshot below and notice:

{"user": ["Incorrect type. Expected pk value, received str."]}

在此处输入图片说明

Back to your problem, you have the following in your .sendData() :

x = {
      id: 0,
      dimension_id: dimension.id,
      item_id: item.id,
      usuario_id: 1
    }

Which you then call JSON.stringify() on. If dimension.id and item_id are both integer (a reasonable assumption), then you're passing the following as a payload:

JSON.stringify(x)
# returns:
"{"id":0,"dimension_id":1,"item_id":2,"usuario_id":3}"

Your Django Model for FiltroUsuarios defined these columns / fields, so you now need to check both your models and FiltroUsuariosSerializers that these are expected value / value types mapping to these columns.

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