programing

js 또는 jQuery를 사용하여 Ajax 요청에 커스텀 HTTP 헤더를 추가하려면 어떻게 해야 합니까?

goodjava 2023. 2. 3. 20:08

js 또는 jQuery를 사용하여 Ajax 요청에 커스텀 HTTP 헤더를 추가하려면 어떻게 해야 합니까?

JavaScript 또는 jQuery를 사용하여 커스텀HTTP 헤더를 추가하거나 작성하는 방법을 알고 있는 사람이 있습니까?

필요한 것에 따라 몇 가지 솔루션이 있습니다.

개별 요구에 커스텀헤더(또는 헤더세트) 추가하려면headers속성:

// Request with custom header
$.ajax({
    url: 'foo/bar',
    headers: { 'x-my-custom-header': 'some value' }
});

모든 요청에 기본 헤더(또는 헤더 세트)를 추가하려면$.ajaxSetup():

$.ajaxSetup({
    headers: { 'x-my-custom-header': 'some value' }
});

// Sends your custom header
$.ajax({ url: 'foo/bar' });

// Overwrites the default header with a new header
$.ajax({ url: 'foo/bar', headers: { 'x-some-other-header': 'some value' } });

모든 요구에 헤더(또는 헤더 세트) 추가하려면beforeSend와 교제하다.$.ajaxSetup():

$.ajaxSetup({
    beforeSend: function(xhr) {
        xhr.setRequestHeader('x-my-custom-header', 'some value');
    }
});

// Sends your custom header
$.ajax({ url: 'foo/bar' });

// Sends both custom headers
$.ajax({ url: 'foo/bar', headers: { 'x-some-other-header': 'some value' } });

편집(자세한 정보):한 가지 유의할 점은 다음과 같습니다.ajaxSetup정의할 수 있는 기본 헤더 세트는 1개뿐이고 정의할 수 있는 것은 1개뿐입니다.beforeSend당신이 전화하면ajaxSetup몇 번이고 마지막 헤더세트만 전송되고 마지막 전송 전 콜백만 실행됩니다.

또는 향후 모든 요청에 대해 커스텀헤더를 송신하는 경우는, 다음을 사용할 수 있습니다.

$.ajaxSetup({
    headers: { "CustomHeader": "myValue" }
});

이렇게 하면 요청 옵션에 의해 명시적으로 재정의되지 않는 한 향후 모든 Ajax 요청에는 커스텀헤더가 포함됩니다.자세한 것은, 을 참조해 주세요.ajaxSetup 여기서

jQuery를 사용하지 않고도 이 작업을 수행할 수 있습니다.XMLHttpRequest의 송신 메서드를 덮어쓰고 헤더를 추가합니다.

XMLHttpRequest.prototype.realSend = XMLHttpRequest.prototype.send;
var newSend = function(vData) {
    this.setRequestHeader('x-my-custom-header', 'some value');
    this.realSend(vData);
};
XMLHttpRequest.prototype.send = newSend;

JQuery ajax를 가정하여 다음과 같은 커스텀헤더를 추가할 수 있습니다.

$.ajax({
  url: url,
  beforeSend: function(xhr) {
    xhr.setRequestHeader("custom_header", "value");
  },
  success: function(data) {
  }
});

다음은 XHR2의 사용 예를 제시하겠습니다.

function xhrToSend(){
    // Attempt to creat the XHR2 object
    var xhr;
    try{
        xhr = new XMLHttpRequest();
    }catch (e){
        try{
            xhr = new XDomainRequest();
        } catch (e){
            try{
                xhr = new ActiveXObject('Msxml2.XMLHTTP');
            }catch (e){
                try{
                    xhr = new ActiveXObject('Microsoft.XMLHTTP');
                }catch (e){
                    statusField('\nYour browser is not' + 
                        ' compatible with XHR2');                           
                }
            }
        }
    }
    xhr.open('POST', 'startStopResume.aspx', true);
    xhr.setRequestHeader("chunk", numberOfBLObsSent + 1);
    xhr.onreadystatechange = function (e) {
        if (xhr.readyState == 4 && xhr.status == 200) {
            receivedChunks++;
        }
    };
    xhr.send(chunk);
    numberOfBLObsSent++;
}; 

도움이 됐으면 좋겠다.

오브젝트를 작성할 경우 setRequest를 사용할 수 있습니다.요청을 보내기 전에 이름과 값을 할당하는 헤더 함수.

의 사용은 피해야 합니다.$.ajaxSetup()문서에 기술된 바와 같이요.대신 다음을 사용하십시오.

$(document).ajaxSend(function(event, jqXHR, ajaxOptions) {
    jqXHR.setRequestHeader('my-custom-header', 'my-value');
});

"Ajax 사용 시" 및 "HTTP 요청 헤더"를 의미한다고 가정하고,headers전달 대상 개체의 속성ajax()

헤더(1.5 추가)

디폴트:{}

요청과 함께 보내는 추가 헤더 키/값 쌍의 맵.이 설정은 beforeSend 함수를 호출하기 전에 설정됩니다.따라서 헤더 설정의 값은 beforeSend 함수 내에서 덮어쓸 수 있습니다.

- http://api.jquery.com/jQuery.ajax/

"setRequest(설정요구)XMLHttpRequest 객체의 Header" 메서드를 사용해야 합니다.

http://help.dottoro.com/ljhcrlbv.php

js fetch를 사용할 수 있습니다.

async function send(url,data) {
  let r= await fetch(url, {
        method: "POST", 
        headers: {
          "My-header": "abc"  
        },
        body: JSON.stringify(data), 
  })
  return await r.json()
}

// Example usage

let url='https://server.test-cors.org/server?enable=true&status=200&methods=POST&headers=my-header';

async function run() 
{
 let jsonObj = await send(url,{ some: 'testdata' });
 console.log(jsonObj[0].request.httpMethod + ' was send - open chrome console > network to see it');
}

run();

언급URL : https://stackoverflow.com/questions/7686827/how-can-i-add-a-custom-http-header-to-ajax-request-with-js-or-jquery