HTTP标头(Headers)是HTTP请求和响应中的元数据,用于传递额外的信息。自定义HTTP标头允许客户端和服务器之间交换应用特定的信息。
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true);
// 添加自定义标头
xhr.setRequestHeader('X-Custom-Header', 'CustomValue');
xhr.setRequestHeader('Another-Header', 'AnotherValue');
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
}
};
xhr.send();
fetch('https://api.example.com/data', {
method: 'GET',
headers: {
'X-Custom-Header': 'CustomValue',
'Another-Header': 'AnotherValue',
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
$.ajax({
url: 'https://api.example.com/data',
type: 'GET', // 或 'POST'
beforeSend: function(xhr) {
xhr.setRequestHeader('X-Custom-Header', 'CustomValue');
},
success: function(data) {
console.log(data);
},
error: function(error) {
console.error('Error:', error);
}
});
$.ajax({
url: 'https://api.example.com/data',
type: 'GET',
headers: {
'X-Custom-Header': 'CustomValue',
'Another-Header': 'AnotherValue'
},
success: function(data) {
console.log(data);
}
});
Content-Type
, Accept
等),除非你确实需要覆盖它们。如果自定义标头没有生效,检查:
send()
或open()
之前设置了标头没有搜到相关的沙龙