How to enable CORS support in application in QT?

  • I want add CORS support for my application (QML and xhtmlrequest, JSON, RESTAPI, etc)
    I finded this:
    but i dont have idea how i should do it.

    in main.cpp:

    QWebSocketCorsAuthenticator CORS;

    Can you give me a clue?

  • Lifetime Qt Champion

    It seems its via a signal.

    "the QWebSocketCorsAuthenticator class is used in the originAuthenticationRequired() signal"

    So you connect the signal to a slot and when its called, you use the
    authenticator parameter and call setAllowed() on that one.

  • I found this in "QML Global Object" documentation:

    "QML's XMLHttpRequest does not enforce the same origin policy."

  • I read something:

    In 'main.cpp' file I 'copmpose' this:

    QWebSocketCorsAuthenticator *CORS = new QWebSocketCorsAuthenticator("");
         //qDebug() << CORS.allowed();
        QWebSocketServer *CORSrequest = new QWebSocketServer(QStringLiteral("Request"),
        QObject::connect(CORSrequest, &QWebSocketServer::originAuthenticationRequired,
                             CORS, &QWebSocketCorsAuthenticator::allowed);

    Is this the right way?

  • I use QML/XMLHttpRequest

    var req = new XMLHttpRequest();
         'GET', '', true); /* Argument trzeci, wartość true, określa, że żądanie ma być asynchroniczne */
                   req.onreadystatechange = function(aEvt) {
                       if (req.readyState == 4) {
                           if (req.status == 200) {
                               mylabel.text = req.responseText;
                           } else{
                               //showRequestInfo("Błąd podczas ładowania strony\n");
                           mylabel.text = "Błąd podczas ładowania strony\n";}

    It work fine

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.