萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

如何從 jQuery AJAX 請求中移除 X-Requested-With 標頭

背景

jQuery 默認在所有 AJAX 請求中添加 X-Requested-With: XMLHttpRequest 標頭,用於服務端識別 AJAX 請求。某些場景需移除:

  • 對接不識別該標頭的第三方 API
  • 繞過服務端基於此標頭的 CSRF 檢查/限流
  • 測試服務端非 AJAX 邏輯
  • CORS 預檢簡化 (某些情況)

單次請求移除:beforeSend 修改標頭

$.ajax({
    url: 'https://api.example.com/data',
    type: 'GET',
    beforeSend: function(xhr) {
        // 關鍵:設置為空字符串函數,覆蓋默認值
        xhr.setRequestHeader('X-Requested-With', {toString: function() { return ''; }});
        // 或直接刪除 (jQuery 內部允許)
        // xhr.setRequestHeader('X-Requested-With', '');
    },
    success: function(data) {
        console.log('無 X-Requested-With 請求成功:', data);
    }
});

全局移除:ajaxSetup / ajaxSend

// 方式 1:ajaxSetup (影響所有後續 $.ajax)
$.ajaxSetup({
    beforeSend: function(xhr) {
        xhr.setRequestHeader('X-Requested-With', {toString: function() { return ''; }});
    }
});

// 方式 2:全局事件 ajaxSend (更靈活,可條件判斷)
$(document).on('ajaxSend', function(event, xhr, settings) {
    // 可根據 URL 等條件決定是否移除
    if (settings.url.indexOf('/third-party/') === 0) {
        xhr.setRequestHeader('X-Requested-With', {toString: function() { return ''; }});
    }
});

原理解析:為什麼要用 {toString: ...}?

// jQuery 內部發送標頭邏輯簡化
function setRequestHeader(xhr, name, value) {
    // value 會被調用 toString()
    xhr.setRequestHeader(name, value + ''); // 或 value.toString()
}

// 如果傳普通空字符串 ''
xhr.setRequestHeader('X-Requested-With', '');
// 瀏覽器實際發送:X-Requested-With: (空值,但標頭仍存在)

// 傳入對象,toString 返回空字符串
xhr.setRequestHeader('X-Requested-With', {toString: function() { return ''; }});
// 瀏覽器發送:X-Requested-With: (空值)
// 某些瀏覽器/代理可能仍保留標頭名

// 徹底移除:原生 fetch / XMLHttpRequest 手動控制
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
// 簡單不設置該標頭即可
xhr.send();

服務端識別 AJAX 的替代方案

若服務端依賴此標頭,移除後需協商替代方案:

方案實現優點
自定義標頭X-API-Request: true語義清晰、可控
Content-Typeapplication/json 等REST 標準
Query 參數?format=json&ajax=1簡單、可見
Accept 標頭Accept: application/jsonHTTP 標準

完整示例:條件移除 + 自定義標頭

$.ajax({
    url: '/api/user/profile',
    type: 'POST',
    data: {action: 'update'},
    dataType: 'json',
    headers: {
        'X-API-Version': '2.1',
        'X-Client-Id': 'web-app'
    },
    beforeSend: function(xhr) {
        // 內部 API 保留 X-Requested-With,第三方 API 移除
        if (this.url.indexOf('/third-party/') >= 0) {
            xhr.setRequestHeader('X-Requested-With', {toString: function() { return ''; }});
        }
    },
    success: function(res) {
        if (res.code === 0) showSuccess(res.data);
        else showError(res.msg);
    },
    error: function(xhr, status, err) {
        if (status === 'abort') return; // 手動取消不提示
        showError('網絡錯誤: ' + err);
    }
});

現代 Fetch API 對比

// fetch 默認不發送 X-Requested-With,完全可控
fetch('/api/data', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'X-API-Version': '2.1'
        // 無 X-Requested-With,除非手動添加
    },
    credentials: 'include', // 攜帶 Cookie
    body: JSON.stringify({key: 'value'})
}).then(res => res.json())
  .then(data => console.log(data))
  .catch(err => console.error(err));

注意事項

  • ⚠️ 移除後服務端 request.isAjax() (Spring/ThinkPHP/Laravel 等) 將返回 false
  • ⚠️ 某些 CSRF 保護依賴此標頭豁免 Token 驗證,移除可能導致 403
  • ✅ 推薦:客戶端統一發送自定義標頭 X-Requested-By: Fetch/jQuery,服務端按新標頭判斷
  • ✅ 測試時用瀏覽器 Network 面板確認 Request Headers 中無 X-Requested-With
copyright © 萬盛學電腦網 all rights reserved