Search code examples
javascriptreact-nativepostaxiosundefined

Axios POST request returned Undefined


I'm trying to build react-native fuction to make POST request to an API using Axios. The function seems to work but i keep getting the response as undefined. I've tested POST request with Postman, it works normally.

{
    "CaThuHoiList": [
        {
            "NGAY": "20-01-2020",
            "TH_ID": 33,
            "CA": 1,
            "CT_DONVI_ID": 78,
            "CREATE_BY": 4797,
            "TRANG_THAI": "HT",
            "CREATE_DATE": "20-01-2020 00:00",
            "KHO_ID": null,
            "LOAI": "TT"
        },
        {
            "NGAY": "20-01-2020",
            "TH_ID": 34,
            "CA": 1,
            "CT_DONVI_ID": 78,
            "CREATE_BY": 4797,
            "TRANG_THAI": "BD",
            "CREATE_DATE": "20-01-2020 00:00",
            "KHO_ID": null,
            "LOAI": "TL"
        }
    ],
    "Status": 1,
    "Message": ""
}

However i couldn't get the same response (undefined) while running my function:

onPostJson = () => {
  axios.post('https://10.1.127.17:11111/vpdu/get-ca-thu-hoi', {
        headers: {
            'Content-Type': 'application/json',
            Accept: 'application/json',
        },
        body: JSON.stringify({
          FromDate: "01-Jan-2020",
          ToDate: "01-Feb-2020",
          Ca: 1
        })
    })
    .then(function (response) {
      data = response;
      console.log(data); \\Storing response in data still getting undefined
      return response;
    })
    .catch(function (error) {
      console.log(error);
    });
}

Could anyone tell me what is the problem? Thanks in advance.


Solution

  • You need to have data pulled out. I have done the changes. You may check out.

         onPostJson = () => {
             let configObject = {
            "url": "https://10.1.127.17:11111/vpdu/get-ca-thu-hoi",
            "method": "post",
            "headers": {
     'Content-Type': 'application/json'
    },
    "data":{
                      "FromDate": "01-Jan-2020",
                      "ToDate": "01-Feb-2020",
                      "Ca": 1
                    }
            
        }}
    axios.request(configObject ).then((res) => {
              console.log("react1: ", res);
              console.log("react2: ", res.data);
              
          })
    }