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: http://doc.qt.io/qt-5/qwebsocketcorsauthenticator.html
    but i dont have idea how i should do it.

    in main.cpp:

    QWebSocketCorsAuthenticator CORS;
    CORS.setAllowed(true);
    

    Can you give me a clue?


  • Qt Champions 2016

    @Pyroxar
    Hi
    It seems its via a signal.

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

    http://doc.qt.io/qt-5/qwebsocketserver.html#originAuthenticationRequired

    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:
    http://doc.qt.io/qt-5/echoserver.html
    http://doc.qt.io/qt-5/signalsandslots.html

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

    QWebSocketCorsAuthenticator *CORS = new QWebSocketCorsAuthenticator("https://jsonplaceholder.typicode.com/photos/");
        CORS->setAllowed(true);
         //qDebug() << CORS.allowed();
    
        QWebSocketServer *CORSrequest = new QWebSocketServer(QStringLiteral("Request"),
                                                             QWebSocketServer::SecureMode);
        CORSrequest->originAuthenticationRequired(CORS);
    
        QObject::connect(CORSrequest, &QWebSocketServer::originAuthenticationRequired,
                             CORS, &QWebSocketCorsAuthenticator::allowed);
    

    Is this the right way?



  • I use QML/XMLHttpRequest

    var req = new XMLHttpRequest();
                   req.open('GET', 'http://www.kacperpaczos.pl/skryptwphpie/?cors', true); /* Argument trzeci, wartość true, określa, że żądanie ma być asynchroniczne */
                   req.onreadystatechange = function(aEvt) {
                       if (req.readyState == 4) {
                           if (req.status == 200) {
                               //showRequestInfo(req.responseText);
                               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