Miguel Lorenzo
Miguel Lorenzo

Reputation: 560

nativescript-background-http get response body

I am currently using nativescript-background-http to upload images and I was just wondering is there a way to get the response body or response header coming from the server after sending the image?

Upvotes: 4

Views: 1032

Answers (3)

Ashg
Ashg

Reputation: 2716

The way I was able to get the response back from the server was in the complete method use the getBodyAsString() method and parse it.

 task.on("complete", (ev: any) =>  {
                console.log("Upload complete");
                let sr = JSON.parse(ev.response.getBodyAsString());                  
         });

Upvotes: 1

HannesT117
HannesT117

Reputation: 141

Just in case someone has the same problem a year later:

task.on("responded", (e) => {
   JSON.parse(e.data)
}

Upvotes: 3

Nick Iliev
Nick Iliev

Reputation: 9670

function sendImages(uri, fileUri) {

    imageName = extractImageName(fileUri);

    var request = {
        url: "http://httpbin.org/post",
        method: "POST",
        headers: {
            "Content-Type": "application/octet-stream",
            "File-Name": imageName
        },
        description: "{ 'uploading': " + imageName + " }"
    };

    var task = session.uploadFile(fileUri, request);

    task.on("progress", logEvent);
    task.on("error", logEvent);
    task.on("complete", logEvent);

    function logEvent(e) {      
        console.log("----------------");
        console.log('Status: ' + e.eventName);
        // console.log(e.object);
        if (e.totalBytes !== undefined) {
            console.log('current bytes transfered: ' + e.currentBytes);
            console.log('Total bytes to transfer: ' + e.totalBytes);
        }  
    }

    return task;
}

Based on this demo

Upvotes: 0

Related Questions