【问题标题】:How to add header to request in Jquery Ajax?如何在 Jquery Ajax 中向请求添加标头?
【发布时间】:2017-06-15 05:47:23
【问题描述】:

我正在尝试使用 JQuery 在 Ajax 中为请求添加标头。

下面是代码:-

$.ajax({
    类型:“发布”,
    内容类型:“应用程序/json”,
    url: "http://localhost:8080/core-service/services/v1.0/patients/registerPatients",
    数据:JSON.stringify(耐心DTO),
    //跨域:真,
    数据类型:'json',
    标头:{“X-AUTH-TOKEN”:tokken},
    成功:功能(耐心DTO){
        console.log("成功:", PatientDTO);
        /* location.href = "fieldagentHRA.html";*/
        如果(类型(存储)!==“未定义”){
            localStorage.setItem("patUrn", patientDTO.data);
            location.href="fieldagentHRA.html";
        }
    },
    错误:函数(e){
    console.log("错误:", e);
    显示(e);
    },
    完成:函数(e){
    启用注册按钮(真);
    }
});

我用 chrome 检查了这个,发现没有添加标题的正文。

然后我使用了RequestlyRequestly 是 chrome+firefox 插件,我们可以使用它手动为请求添加标头)。

手动添加标题后:-

在两张图片中,请求标头 x-auth-token 都存在于“ACCESS-CONTROL-REQUEST-HEADERS”中,但“X-AUTH-TOKEN”标头以及标头值存在于第二张图片中,而第二张图片中不存在第一张照片。

所以我的问题是如何使用 JQuery 在 Ajax 中添加请求标头?

【问题讨论】:

    标签: ajax header request-headers jquery-ajaxq


    【解决方案1】:

    有几个解决方案取决于你想要做什么

    如果想为单个请求添加自定义标头(或一组标头),只需添加 headers 属性,这将帮助您发送带有标头的请求。

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

    如果想为每个请求添加一个默认标头(或一组标头),请使用$.ajaxSetup(): 这将帮助您添加标头。

    //Setup headers here and than call ajax
    $.ajaxSetup({
        headers: { 'x-my-custom-header': 'some value' }
    });
    
    // Sends your ajax
    $.ajax({ url: 'foo/bar' });
    

    为每个请求添加一个标头(或一组标头),然后将 beforeSend 钩子与 $.ajaxSetup() 一起使用:

    //Hook your headers here and set it with before send function.
    $.ajaxSetup({
        beforeSend: function(xhr) {
            xhr.setRequestHeader('x-my-custom-header', 'some value');
        }
    });
    
    // Sends your ajax
    $.ajax({ url: 'foo/bar' });
    

    Reference Link : AjaxSetup

    Reference Link : AjaxHeaders

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-13
      • 1970-01-01
      相关资源
      最近更新 更多