programing

아약스 요청에서 X-Requested-With 헤더를 제거할 수 있습니까?

lastcode 2023. 7. 31. 21:25
반응형

아약스 요청에서 X-Requested-With 헤더를 제거할 수 있습니까?

jquery(또는 plain JS)에서 작성한 ajax 요청에서 'X-Requested-With' 헤더를 제거하려고 시도한 경험이 있는 사람이 있는지 알고 싶습니다. 가능한가요?

두 번째 파트: 그리스 몽키의 아약스 요청이 이 헤더를 설정했는지 알고 있습니까?

감사해요.

헤더는 다음과 같습니다.

X-Requested-With XMLHttpRequest

@vamp에서 제안한 jQuery의 헤더 제거 솔루션은 올바른 방향으로 가고 있지만, 다른 사람들이 말했듯이 여전히 빈 X-Requested-With 헤더가 전송됩니다.

beforeSend 콜백은 Send가 호출되기 전까지 인스턴스화되지 않은 실제 XMLHttpRequest 개체(xhr)가 아닌 jQuery의 XHR 개체(jqXHR)를 수신합니다.

요청 설정jqXHR의 헤더 메서드는 헤더를 개체에 추가한 다음 나중에 X-Requested-With 항목을 헤더 개체에 추가한 직후 동일한 이름의 xhr 메서드를 사용하여 반복됩니다.

jQuery에서 이 문제가 발생하는 부분은 다음과 같습니다.

if ( !options.crossDomain && !headers["X-Requested-With"] ) {
    headers["X-Requested-With"] = "XMLHttpRequest";
}

for ( i in headers ) {
    xhr.setRequestHeader( i, headers[ i ] );
}

이로 인해 문제가 발생합니다.X-Requested-With 헤더를 지정하지 않으면 jQuery가 실행됩니다(crossDomain 설정이 false로 평가되지만 원하는 솔루션이 아닐 수도 있음).그런 다음 즉시 xhr 헤더를 설정합니다. 이 헤더는 설정을 해제할 수 없습니다.


jQuery.jax로 X-Requested-With 헤더를 보내지 않으려면:

jQuery.ajax는 xhr이라는 설정을 제공합니다. xhr은 XMLHttpRequest 개체를 생성하기 위한 jQuery의 기본 제공 팩토리 메서드를 재정의합니다.이 공장 방법을 래핑한 다음 브라우저의 기본 세트Request를 래핑합니다.헤더 메서드, X-Requested-With 헤더를 설정하기 위한 jQuery의 호출은 무시할 수 있습니다.

jQuery.ajax({

    url: yourAjaxUrl,

    // 'xhr' option overrides jQuery's default
    // factory for the XMLHttpRequest object.
    // Use either in global settings or individual call as shown here.
    xhr: function() {
        // Get new xhr object using default factory
        var xhr = jQuery.ajaxSettings.xhr();
        // Copy the browser's native setRequestHeader method
        var setRequestHeader = xhr.setRequestHeader;
        // Replace with a wrapper
        xhr.setRequestHeader = function(name, value) {
            // Ignore the X-Requested-With header
            if (name == 'X-Requested-With') return;
            // Otherwise call the native setRequestHeader method
            // Note: setRequestHeader requires its 'this' to be the xhr object,
            // which is what 'this' is here when executed.
            setRequestHeader.call(this, name, value);
        }
        // pass it on to jQuery
        return xhr;
    },

    success: function(data, textStatus, jqXHR) {
        // response from request without X-Requested-With header!
    }

    // etc...

});

왜 안 되나요?시도:

(function(){
    $.ajaxSettings.beforeSend=function(xhr){
        xhr.setRequestHeader('X-Requested-With', {toString: function(){ return ''; }});
    };
})(jQuery);

행운을 빕니다.

jQuery에서 이 작업을 수행하려면 요청을 교차 도메인으로 설정합니다.예:

server.sys

<?='<pre>'.print_r($_SERVER,1);?>

client.js

$.ajax({ url: 'server.php', crossDomain: true }).success(function(r){document.write(r)})

"두 번째 부분: 그리스 몽키의 아약스 요청이 이 헤더를 설정했는지 알고 있습니까?"

아니요, Greasemonkey에서는 이 헤더를 설정하지 않습니다(확실히 추가할 수 있지만).

실행된 기본 요청GM_xmlhttpRequest()일반적인 브라우저 요청과 똑같이 보입니다.
예:

GM_xmlhttpRequest
({
    method:     "GET",
    url:        "http://google.com/",
    onload:     function(response) {alert(response.responseText); }
});

내 패킷 스니퍼에게는 이렇게 보입니다.

GET / HTTP/1.1
    Request Method: GET
    Request URI: /
    Request Version: HTTP/1.1
Host: google.com
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: UTF-8,*
Keep-Alive: 115
Connection: keep-alive
Cookie: blah, blah, blah, blah, blah...

jQuery는 현재 이를 위한 방법을 공개하지 않고, 얼마 전 파이어폭스 오류와 관련된 티켓이 있었지만, 옵션으로 삼기보다는 파이어폭스에서 오류 문제를 수정했습니다.

궁금하다면 여기에서 추가된 위치를 볼 수 있지만 jQuery core: http://github.com/jquery/jquery/blob/master/src/ajax.js#L370 를 편집/삭제하지 않고는 제거할 수 없습니다.

이를 고려할 수 있습니다.

$.ajax({
  url: 'http://fiddle.jshell.net/favicon.png',
  beforeSend: function( xhr ) {
    xhr.setRequestHeader('X-Requested-With', {toString: function(){ return ''; }});
  },
  success: function( data ) {
    if (console && console.log){
      console.log( 'Got data without the X-Requested-With header' );
    }
  }
});

언급URL : https://stackoverflow.com/questions/3372962/can-i-remove-the-x-requested-with-header-from-ajax-requests

반응형