如何在 qml XmlHttpRequest 中设置用户名和密码

How to set username and password in a qml XmlHttpRequest

我想在带有 QML 的 QT-Creator 中使用 javascript XMLHttpRequest 连接到服务器上的 xml(例如 nextcloud)。但是需要用户名和密码。 下面是来自 QML-Book 的修改示例。但是我不知道如何为不同的 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()
    }
}

我找到了类似问题的答案,例如:

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

但它不起作用它给我:"btoa" 未定义。

btoa is a QML function that belongs to the global Qt对象,所以必须把代码改成:

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();