WordPress

php — dlaczego to wywołanie zwrotne ajax do punktu końcowego REST jest nadal blokowane przez „nosniff” z powodu niezgodności typu MIME („application/json”)?

  • 18 marca, 2023
  • 3 min read
php — dlaczego to wywołanie zwrotne ajax do punktu końcowego REST jest nadal blokowane przez „nosniff” z powodu niezgodności typu MIME („application/json”)?


uruchamiam WP na serwerze nginx

skonfigurowałem punkt końcowy odpoczynku, ukierunkowany na wywołanie zwrotne ajax

jeśli włączę typowy „nosniff” XCTO,

more_set_headers   "X-Content-Type-Options: nosniff";

w konfiguracji serwera blokuje

"due to MIME type (“application/json”) mismatch (X-Content-Type-Options: nosniff)"

jeśli usunę nagłówek XCTO, problem zniknie

brakuje mi tego, co nie jest poprawnie wpisane na mojej stronie

z tym szablonem,

<?php

function MY_login_ajax_action_callback( $request ){
    $response = array(
        'data'  => 'success',
        'supplemental' => array(
            'message' => 'success'
        )
    ) ;
    $response = serialize($response);
    header('Content-Type: text/javascript; charset=utf-8');
    $response = json_encode($response);

    return rest_ensure_response( $response );
}
add_action(
    'rest_api_init',
    function () {
        register_rest_route(
            'test-rest/v1',
            '/verify/',
            array(
                'methods'  => 'POST',
                'callback' => 'my_ajax_action_callback'
            )
        );
    }
);

function add_footer_js() {
    $myAjaxData = [
        'root'            => esc_url_raw( rest_url() ),
        'route'           => 'test-rest/v1/verify/',
        'nonce'           => wp_create_nonce( 'wp_rest' ),
        'success'         => 'success!',
        'failure'         => 'failure!',
        'app_usr'         => MY_APP_USR,
        'app_pwd_name'    => MY_APP_PWD_NAME,
        'app_pwd'         => MY_APP_PWD,
        'app_token'       => MY_APP_TOKEN,
    ];
?>

    <script type="application/json" id="myAjaxData" >
        <?php echo json_encode( $myAjaxData, JSON_UNESCAPED_SLASHES ) ?>
    </script>

    <script type="text/javascript">
        var myAjaxData = JSON.parse(document.getElementById('myAjaxData').textContent);
        console.log('myAjaxData:    ' + JSON.stringify(myAjaxData, null, "\t"));

    jQuery( "#myform" ).submit(function(e) {
        var myE = e;
        const mySubmitContinue="yes";
        if ( mySubmitContinue === 'no') {
            alert( "Handler for .submit() : HALT" );
            e.preventDefault();
        } else {
            alert( "Handler for .submit() : CONTINUE" );
        }
    });

    jQuery('#wp-submit').on('click', function(e) {
        var myE = e;
        var formData = jQuery('#myform').serializeArray();
        var data = {
            action: 'my_ajax_action',
            dataForPHP: formData
        };
        var myAjaxUrl = myAjaxData.root + myAjaxData.route;

        jQuery.ajax({

            url: myAjaxUrl,
            method: 'POST',
            dataType: 'jsonp',
            contentType: 'text/javascript; charset=UTF-8',

            async: false,
            data: data,
            cache: false,
            crossDomain: true,
            headers: {
                'Cache-Control': 'no-cache, no-store, must-reverify',
                'Pragma': 'no-cache',
                'Expires': '0'
            },
            beforeSend: function( xhr ) {
                xhr.overrideMimeType( "text/javascript; charset=UTF-8" );
                xhr.setRequestHeader('Authorization', 'Basic ' + myAjaxData.app_token);
            },
        })
        .done(function ( response ) {
            console.log( 'AJAX success:    ' + JSON.stringify(response, null, "\t") );
        })
        .fail(function ( response ) {
            console.log( 'AJAX error:      ' + JSON.stringify(response, null, "\t") );
        })
        .always(function( response ) {
            //
        });

    });
    </script>
<?php
    return;
}
add_action('wp_footer', 'add_footer_js' );

if ( ! is_user_logged_in() ) {
    $args = array (
        'form_id'        => 'myform',
        'redirect'       => home_url(),
        'label_username' => __( 'User: ' ),
        'label_password' => __( 'Pass: ' ),
        'label_log_in'   => __( 'LogIn' ),
        'remember'       => false,
        'value_remember' => false
    );
    wp_login_form( $args );
} else {
    nocache_headers();
    wp_safe_redirect( home_url() );
    exit();
}

przy obciążeniu, w konsoli

myAjaxData:    {
    "root": "
    "route": "my-rest/v1/verify/",
    "nonce": "abcde12345",
    "success": "success!",
    "failure": "failure!",
    "app_usr": "myadmin",
    "app_pwd_name": "my-login-rest-api",
    "app_pwd": "xxx...xxx",
    "app_token": "cfa...Cf="
}

następnie kliknij, aby przesłać, w konsoli

The resource from “ was blocked due to MIME type (“application/json”) mismatch (X-Content-Type-Options: nosniff).

AJAX error:      {
    "readyState": 4,
    "status": 404,
    "statusText": "error"
}

i alerty

"Handler for .submit() : CONTINUE"

co jest blokowane? gdzieś tam musi być inna specyfikacja treści. ale co i gdzie?

Warto przeczytać!  Jak dodać polecaną miniaturę do importu XML przy użyciu obrazu adresu URL?


Źródło