DCR
DCR

Reputation: 15685

how to return server response from axios

I've looked at some of the other posts on this and it seems I need to apply 'await' I'm just not sure how to modify the following to do that

function sendData(url,emailPass){

    let bodyFormData = new FormData()
    for (const [key, value] of Object.entries(emailPass)) {
        console.log(key,value)
        bodyFormData.append(key,value)
    }

        
    axios({
        method: 'POST',
        url: url,
        data: bodyFormData,
        headers: {'Content-Type': 'multipart/form-data'}
    })
        .then(function (response){
            return response.data

        })
        .catch(function(response){
            return response
        })

}

Upvotes: 1

Views: 275

Answers (1)

cactus
cactus

Reputation: 447

You should modify the function to return the promise from axios, which returns the response data.

function sendData(url,emailPass){

    let bodyFormData = new FormData()
    for (const [key, value] of Object.entries(emailPass)) {
        console.log(key,value)
        bodyFormData.append(key,value)
    }

        
    return axios({
        method: 'POST',
        url: url,
        data: bodyFormData,
        headers: {'Content-Type': 'multipart/form-data'}
    })
        .then(function (response){
            return response.data

        })
        .catch(function(response){
            return response
        })

}

If you want to use async/await you can do

async function sendData(url,emailPass){

    let bodyFormData = new FormData()
    for (const [key, value] of Object.entries(emailPass)) {
        console.log(key,value)
        bodyFormData.append(key,value)
    }
    
    try{
        const response = await axios({
            method: 'POST',
            url: url,
            data: bodyFormData,
            headers: {'Content-Type': 'multipart/form-data'}
        });
        return response.data;
    }catch(e){
        return e.response.data;   
    }
}

Upvotes: 1

Related Questions