1
votes

I create a rest api with vuejs and django rest framework. The probleme is when i made a post request. With a get request he works but not with a post request.

axios
      .get('http://127.0.0.1:8000/api/users/')
      .then(response => (this.info = response.data))
axios
      .post('http://127.0.0.1:8000/api/users/', {
        params : {
          email : "[email protected]",
          username : 'test'
        }
      })
      .then(response => (this.info = response.data))
class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all().order_by('-date_joined')
    serializer_class = UserSerializer
router = routers.DefaultRouter()
router.register(r'users', UserViewSet)

urlpatterns = [
    path('', include(router.urls)),
]

My get request works but not my post request. In my console i have : http://127.0.0.1:8000/api/users/?username=test&[email protected] 400 (Bad Request) And when i watch network i have {"username":["This field is required."]}

I don't uderstand why i have this error.

1

1 Answers

3
votes

Params in axios are for query string

Try

  axios
    .post('http://127.0.0.1:8000/api/users/', {
      email : "[email protected]",
      username : 'test'
    })
    .then(response => (this.info = response.data))

When posting you don't wanna send your information as a querystring, but as data.

Another signature would be

axios({
  method: 'post',
  url: 'http://127.0.0.1:8000/api/users/',
  data: {
    email : "[email protected]",
    username : 'test'
  }
}).
.then(response => (this.info = response.data))

You can check out the documentation here: https://github.com/axios/axios#example

So the reason you get "username is required" because your server is reading the data/payload, not the querystring. It doesn't find any username sent and lets you know.