js脚本写一个get请求需要包含请求头和url
以下是一个示例get请求的js脚本,包含请求头和url:
const http = new XMLHttpRequest();
const url = 'https://example.com/api/data';
const headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer <token>'
};
http.open('GET', url, true);
for (const key in headers) {
http.setRequestHeader(key, headers[key]);
}
http.onreadystatechange = function() {
if (http.readyState === 4 && http.status === 200) {
console.log(http.responseText);
}
}
http.send();
在此示例中,我们使用XMLHttpRequest对象来发起get请求。我们将url设置为'https://example.com/api/data',并将请求头设置为包含Content-Type和Authorization的对象。我们使用open()方法打开GET请求,并使用setRequestHeader()方法将每个请求头添加到请求中。onreadystatechange方法检测请求状态和响应,并在状态为4(请求已完成)且状态码为200(OK)时打印响应。最后,我们使用send()方法发送请求。
原文地址: https://www.cveoy.top/t/topic/bLi1 著作权归作者所有。请勿转载和采集!