如何在JqueryAjax中添加header请求?

How to add header to request in Jquery Ajax?

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

下面是代码:-

$.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 检查了这个,发现没有添加 header 的 body。

然后我用了RequestlyRequestly是chrome+firefox插件,我们可以手动在requestheader中添加一个header) .

手动添加后header:-

在图片请求中,header x-auth-token 出现在 "ACCESS-CONTROL-REQUEST-HEADERS" 中,但 "X-AUTH-TOKEN" header 以及 header 值出现在第二张图,第一张图没有。

所以我的问题是如何在 Ajax 和 JQuery 中添加请求 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