1

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 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

No problem, if this worked for you then I would appreciate you marking the answer as the correct one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.