codememo

XMLHtpRequest가 헤더를 추가하지 않음 - "X-Requested-With: XMLHtpRequest"

tipmemo 2023. 10. 15. 17:23
반응형

XMLHtpRequest가 헤더를 추가하지 않음 - "X-Requested-With: XMLHtpRequest"

jQuery.ajax()를 사용하여 mvc 액션에 대한 요청을 한 ajax call이 있습니다.이 모든 것이 잘 작동했습니다.하지만 일부 형태의 파일 컨트롤 때문에 jQuery.jax()를 사용하는 것에서 XMLHttpRequest를 사용하여 HTML5 File API를 사용하여 전송하는 것으로 변경했습니다.

이 변경을 수행한 이후로 MVC 작업 메서드는 더 이상 ajax 요청으로 보지 않습니다.Fiddler2를 사용하면 더 이상 요청에 "X-Requested-With: XMLHttpRequest"를 추가하지 않는다는 것을 알게 되었고, 이것이 문제라고 생각합니다.

제가 보내려는 양식은 파일 입력이 없고 일반 텍스트 상자 등만 포함되어 있지만, 두 가지를 모두 처리하기 위해 메소드를 일반적으로 유지하려고 했습니다.아약스 요청을 보낼 때 사용하는 코드는 다음과 같습니다.

// get the edit tender form
var $Form = $Button.closest('form');
var Url = $Form.attr('action');
var AjaxRequestObject = new XMLHttpRequest();
var FormDataToSend = new FormData();

$Form.find(':input').each(function () {
    if ($(this).is('input[type="file"]')) {
        var files = $(this)[0].files;
        if (files.length > 0) {
            FormDataToSend.append(this.name, files[0]);
        }
    } else {
        FormDataToSend.append(this.name, $(this).val());
    }
});

AjaxRequestObject.open('POST', Url, true);
AjaxRequestObject.onreadystatechange = function () {
    if (AjaxRequestObject.readyState == 4) {
        // handle response.
        if (AjaxRequestObject.status == 200) {
            if (!AjaxErrorExists(AjaxRequestObject.responseText, )) {
                alert("success");
                console.log(AjaxRequestObject.responseText);
            }
            else {
                alert('failure');
            }
        }
        else {
            alert('failure');
        }
    }
};

AjaxRequestObject.send(FormDataToSend);

이 코드는 다린 디미트로프가 해결책을 제공한 문제에 따라 제공된 것이라 파일 입력을 ajax로 보낼 수 있었습니다.

이 요청이 아약스 콜에 대한 헤더를 보내지 않는 이유를 알고 있습니까?

X-Requested-WithjQuery에 의해 자동으로 추가됩니다.사용자가 직접 추가할 수 있습니다.AjaxRequestObject.setRequestHeader(). 문서

요청이 다음과 같은지 탐지하는 데 문제가 있었습니다.ajax. 그럼 이 샘플을 통해 1~2분 정도 시간을 절약할 수 있을 겁니다

var xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', URL, true);  // `true` for async call, `false` for sync.

// The header must be after `.open()`, but before `.send()`
xmlhttp.setRequestHeader('X-Requested-With', 'XMLHttpRequest');

xmlhttp.onreadystatechange = function() {
    // 4th state is the last:
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { ... }
};
xmlhttp.send();

로 테스트했습니다.

다음과 같이 모든 XMLHtpRequest.open 메서드 호출을 기본적으로 재정의하고 X-Requested-With 헤더에 추가할 수 있습니다.

(function () {  

    // @author https://github.com/stopsopa jfdsa78y453cq5hjfd7s877834h4h3

    if (window.XMLHttpRequest.prototype.onOpen)  {
        return console.log('XMLHttpRequest.onOpen is already defined');
    }

    function over(method, on, off) {

        var old = window.XMLHttpRequest.prototype[method];

        if (!old.old) {

            var stack = [];

            window.XMLHttpRequest.prototype[on] = function (fn) {
                if (typeof fn === 'function') {
                    stack.push(fn);
                }
            }

            window.XMLHttpRequest.prototype[off] = function (fn) {
                for (var i = 0, l = stack.length ; i < l ; i += 1 ) {
                    if (stack[i] === fn) {
                        stack.splice(i, 1);
                        break;
                    }
                }
            }

            window.XMLHttpRequest.prototype[method] = function () {
                var args = Array.prototype.slice.call(arguments);

                var ret = old.apply(this, args);

                for (var i = 0, l = stack.length ; i < l ; i += 1 ) {
                    stack[i].apply(this, args);
                }

                return ret;
            }

            window.XMLHttpRequest.prototype[method].old = old;
        }
    }

    over('open', 'onOpen', 'offOpen')

    XMLHttpRequest.prototype.onOpen(function () {
        this.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
    });
}());

언급URL : https://stackoverflow.com/questions/12533435/xmlhttprequest-not-adding-header-x-requested-with-xmlhttprequest

반응형