如何用Javascript发出HTTP请求?
时间: 2023-11-28 07:06:01 浏览: 29
可以使用浏览器内置的XMLHttpRequest对象或者使用第三方库(例如axios、fetch)来发出HTTP请求。下面是使用XMLHttpRequest对象发出GET请求的示例代码:
```javascript
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://example.com/api/data');
xhr.onload = function() {
if (xhr.status === 200) {
console.log(xhr.responseText);
} else {
console.log('请求失败。');
}
};
xhr.send();
```
如果需要发送POST请求,需要设置请求头和请求体:
```javascript
const xhr = new XMLHttpRequest();
xhr.open('POST', 'https://example.com/api/data');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function() {
if (xhr.status === 200) {
console.log(xhr.responseText);
} else {
console.log('请求失败。');
}
};
const data = { name: 'John', age: 30 };
xhr.send(JSON.stringify(data));
```
使用第三方库发送HTTP请求的示例代码:
使用axios库:
```javascript
axios.get('https://example.com/api/data')
.then(function(response) {
console.log(response.data);
})
.catch(function(error) {
console.log(error);
});
axios.post('https://example.com/api/data', {
name: 'John',
age: 30
})
.then(function(response) {
console.log(response.data);
})
.catch(function(error) {
console.log(error);
});
```
使用fetch函数:
```javascript
fetch('https://example.com/api/data', {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
})
.then(function(response) {
if (response.ok) {
return response.json();
} else {
throw new Error('请求失败。');
}
})
.then(function(data) {
console.log(data);
})
.catch(function(error) {
console.log(error);
});
fetch('https://example.com/api/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: 'John',
age: 30
})
})
.then(function(response) {
if (response.ok) {
return response.json();
} else {
throw new Error('请求失败。');
}
})
.then(function(data) {
console.log(data);
})
.catch(function(error) {
console.log(error);
});
```
以上代码仅供参考,具体实现需要根据具体场景进行调整。