我正在尝试使用 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); } });
然后我用了Requestly (RequeSTLy 是 chrome+firefox 插件,我们可以使用它手动向请求添加 header )。
手动添加 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' });
关于ajax - 如何在 Jquery Ajax 中向请求添加 header ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41929654/