ajax - 如何在 Jquery Ajax 中向请求添加 header ?

标签 ajax header request-headers jquery-ajaxq

我正在尝试使用 JQuery 在 Ajax 中向请求添加 header 。

下面是代码:-

$.ajax({
    type: "POST",
    contentType: "application/json",
    url: "http://localhost:8080/core-service/services/v1.0/patients/registerPatients",
    data: JSON.stringify(patientDTO),
    //crossDomain : true,
    dataType: 'json',
    headers: {"X-AUTH-TOKEN" : tokken},
    success: function(patientDTO) {
        console.log("SUCCESS: ", patientDTO);
        /* location.href = "fieldagentHRA.html";*/
        if (typeof(Storage) !== "undefined") {
            localStorage.setItem("patUrn", patientDTO.data);
            location.href="fieldagentHRA.html";
        }
    },
    error: function(e) {
    console.log("ERROR: ", e);
    display(e);
    },
    done: function(e) {
    enableRegisterButton(true);
    }
});

我用chrome检查了这个,发现标题的主体没有被添加。 Without Header Body

然后我用了Requestly (RequeSTLy 是 chrome+firefox 插件,我们可以使用它手动向请求添加 header )。

手动添加 header 后:-

After Manually Adding the header

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

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

最佳答案

根据您想要执行的操作,有几种解决方案

If want to add a custom header (or set of headers) to an individual request then just add the headers property and this will help you to send your request with headers.

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

If want to add a default header (or set of headers) to every request then use $.ajaxSetup(): this will help you to add headers.

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

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

add a header (or set of headers) to every request then use the beforeSend hook with $.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

关于ajax - 如何在 Jquery Ajax 中向请求添加 header ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41929654/

相关文章:

jquery - 如何将ajax数据提交到.js.erbrails

android - 是否可以在 google 文档请求中包含 http header ?

windows - 如果我尝试将 header 编译为没有换行符的包含,为什么 MSVC++ 会给我一个错误? (C++/Windows )

java - 如何在Spring boot中的每个请求中添加具有静态值的特定 header ?

portable-class-library - 在可移植库 (PCL) 上的 Web 服务调用上发送的消息头

javascript - 不重新加载的导航栏

jquery - 单击一个div后,如何停止多个div上的jquery单击功能?

jquery - jQuery ajax 接受 attrib 有什么意义?它实际上有什么作用吗?

virtualhost - 如何获取主机或:authority header in Cro when using HTTP/2

javascript - 尝试将 JQuery 与 CakePHP 1.3 一起使用时运气不佳