1、axios
安装
npm install axios
使用
import axios from 'axios';
export default {
data() {
return {
// 数据
};
},
methods: {
fetchDataFromBackend() {
axios.get('/api/your-endpoint')
.then(response => {
// 处理后端返回的数据
this.someData = response.data;
})
.catch(error => {
console.error('Error fetching data:', error);
});
}
}
};
2、fetch
在浏览器中,fetch
是一种用于发送 HTTP 请求的现代方法。以下是关于浏览器fetch
的介绍:
一、基本用法
fetch
接收一个 URL 作为参数,并返回一个 Promise 对象,该对象在请求完成后解析为一个 Response 对象。
fetch('https://example.com/api/data')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
// 处理返回的数据
console.log(data);
})
.catch(error => {
console.error('There has been a problem with your fetch operation:', error);
});
二、参数设置
-
请求方法和数据
fetch
可以通过配置对象来指定请求方法(如 GET、POST、PUT、DELETE 等)和请求体数据。fetch('https://example.com/api/data', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ key: 'value' }) }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error(error));
-
自定义请求头
可以设置自定义的请求头,用于传递特定的信息给服务器。fetch('https://example.com/api/data', { headers: { 'Authorization': 'Bearer your-token', 'Custom-Header': 'custom-value' } }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error(error));