- 如何使用js(Javascript)发送http请求
你可以使用 JavaScript 内置的XMLHttpRequest
对象或较新的fetch
API 发送 HTTP 请求。以下是使用每种方法发送 GET 请求的示例:
使用 XMLHttpRequest:
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://example.com/data');
xhr.onload = function() {
if (xhr.status === 200) {
console.log(xhr.responseText);
}
};
xhr.send();
使用 fetch:
fetch('https://example.com/data')
.then(response => response.text())
.then(data => console.log(data))
.catch(error => console.error(error));
这两种方法也可以用于发送 POST 请求,只需在请求中设置适当的头信息和数据即可。但是,fetch
的语法更简单,用于处理 POST 请求:
使用 XMLHttpRequest:
const xhr = new XMLHttpRequest();
xhr.open('POST', 'https://example.com/data');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function() {
if (xhr.status === 200) {
console.log(xhr.responseText);
}
};
const data = {key: 'value'};
xhr.send(JSON.stringify(data));
使用 fetch:
fetch('https://example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({key: 'value'})
})
.then(response => response.text())
.then(data => console.log(data))
.catch(error => console.error(error));
- XMLHttpRequest和fetch的区别
XMLHttpRequest
和 fetch
都是 JavaScript 中用于发起 HTTP 请求的 API,但是它们有一些区别。
XMLHttpRequest
对象是在 IE5 中引入的,而fetch
API 是 ES6 中引入的。XMLHttpRequest
是一个更为底层的 API,可以对请求和响应的细节进行更精细的控制,例如,可以在请求过程中随时中断请求。而fetch
API 则更为简单易用,不需要手动构建请求头信息,并且可以方便地使用 Promise 进行异步操作。XMLHttpRequest
可以使用setRequestHeader()
方法设置请求头信息,而fetch
则需要使用配置对象中的headers
属性设置请求头信息。- 在处理请求和响应时,
XMLHttpRequest
需要分别设置onreadystatechange
事件和状态码来检查请求和响应的状态,而fetch
则通过 Promise 提供了更为简洁的方式来处理请求和响应。 fetch
API 提供了对跨域资源共享(CORS)的更好支持,可以自动地处理跨域请求,而XMLHttpRequest
则需要手动设置XMLHttpRequest.withCredentials
属性来处理跨域请求。
综上所述,虽然 XMLHttpRequest
和 fetch
都可以用于发起 HTTP 请求,但是由于 fetch
API 更加简单易用,并且具有更好的跨域支持,因此在开发中推荐使用 fetch
API。