Search code examples
reactjspostgetdjango-rest-frameworkaxios

Where should I write axios code in react?


I would like to have axios work when I click the button. Then, I write code like this.

axiosGet.js

showState = () => {

        axios({
            url: 'http://127.0.0.1:8000/profile/',
            method: 'POST',
        })
        .then(res => {
        console.log(res);
        })
        .catch(err => {
            console.log(err);
        })
    }

...

render() {
     return (
          ...
          <button onClick={this.showState}>Show state</button>
          ...
     )
}

and views.py

class SettingView(viewsets.ModelViewSet) :
    queryset = models.Category.objects.all()
    serializer_class = CategorySerializer

    def get(self, request) :
        return Response("ok")

    def post(self, request, format=None):
        return Response("ok")

No response, no error.

Should I not use axios in ordinary event handler? Or are there any requirements that I must keep in mind when using axios in react?


Solution

  • I believe you have to make get request instead of post. you can get the data in res.data

        axios({
            url: 'http://127.0.0.1:8000/profile/',
            method: 'get',
        })
        .then(res => {
            console.log(res.data);
        })
        .catch(err => {
            console.log(err);
        })