Search code examples
javascriptqtqmlubuntu-touch

How to set username and password in a qml XmlHttpRequest


I want to use in QT-Creator with QML the javascript XMLHttpRequest to connect to a xml on a server (for example nextcloud). But there is a username and password required. Below an modified example from QML-Book . But I don't know how to set username and password for an different url.

import QtQuick 2.5

Rectangle {
    width: 320
    height: 480
    ListView {
        id: view
        anchors.fill: parent
        delegate: Thumbnail {
            width: view.width
            text: modelData.title
            iconSource: modelData.media.m
        }
    }

    function request() {
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function() {
            if (xhr.readyState === XMLHttpRequest.HEADERS_RECEIVED) {
                print('HEADERS_RECEIVED')
            } else if(xhr.readyState === XMLHttpRequest.DONE) {
                print('DONE')
                var json = JSON.parse(xhr.responseText.toString())
                view.model = json.items
            }
        }
        xhr.open("GET", "http://mynextcoudserver/remote.php/dav/files/username/folder");
        xhr.send();
    }

    Component.onCompleted: {
        request()
    }
}

I found answers to similar questions like:

xhr.setRequestHeader( 'Authorization', 'Basic ' + btoa( user + ':' + pass ) )

But it does not work it gives me: "btoa" is not defined.


Solution

  • btoa is a QML function that belongs to the global Qt object, so you must change the code to:

    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = ...
    xhr.setRequestHeader( 'Authorization', 'Basic ' + Qt.btoa( user + ':' + pass ) )
    xhr.open("GET", "http://mynextcoudserver/remote.php/dav/files/username/folder");
    xhr.send();