一个vue项目调用后端接口
时间: 2025-03-21 16:01:28 浏览: 31
### 使用 Axios 和 Fetch 在 Vue 项目中调用后端接口
#### 安装 Axios
为了在 Vue 项目中使用 Axios 进行 HTTP 请求,首先需要通过 npm 或 yarn 来安装 Axios。可以通过以下命令完成安装[^2]:
```bash
npm install [email protected] --save
```
或者如果使用 Yarn,则可以运行:
```bash
yarn add [email protected]
```
#### 封装 Axios 方法
可以在项目的 `utils` 文件夹下创建一个名为 `http.js` 的文件来封装 Axios 方法以便于全局调用。
```javascript
// utils/http.js
import axios from 'axios';
const instance = axios.create({
baseURL: 'https://api.example.com', // 替换为实际的 API 地址
timeout: 10000, // 设置超时时间
});
instance.interceptors.request.use((config) => {
console.log('请求拦截器:', config);
return config;
}, (error) => {
console.error('请求错误:', error);
return Promise.reject(error);
});
instance.interceptors.response.use((response) => {
console.log('响应数据:', response.data);
return response.data; // 返回解包后的 data 部分
}, (error) => {
console.error('响应错误:', error);
return Promise.reject(error);
});
export default instance;
```
这样就可以在整个应用中导入这个实例来进行网络请求操作[^3]。
#### 调用后端接口示例
下面是一个简单的组件例子展示如何利用上述封装好的 Axios 实例向后端发送 GET 请求获取数据以及 POST 请求提交表单数据。
```vue
<template>
<div>
<h1>用户列表</h1>
<ul v-if="users.length">
<li v-for="(user, index) in users" :key="index">{{ user.name }}</li>
</ul>
<form @submit.prevent="handleSubmit">
<input type="text" placeholder="用户名..." v-model="newUser.username"/>
<button type="submit">添加新用户</button>
</form>
</div>
</template>
<script>
import http from '@/utils/http';
export default {
name: 'App',
data() {
return {
users: [],
newUser: { username: '' }
};
},
created() {
this.fetchUsers();
},
methods: {
async fetchUsers() {
try {
const result = await http.get('/users');
this.users = result || [];
} catch(err){
alert(`加载失败 ${err}`);
}
},
async handleSubmit(){
if (!this.newUser.username.trim()) return;
try{
await http.post('/add-user', this.newUser);
this.newUser.username = '';
this.fetchUsers(); // 刷新用户列表
}catch(e){
alert(`保存失败 ${e.message}`);
}
}
}
};
</script>
```
#### 关于 Fetch API
Fetch 是一种现代浏览器内置的方法用于发起网络请求,无需额外依赖库即可执行基本功能。然而相比起 Axios 提供更丰富的特性支持如自动转换 JSON 数据、取消请求等功能,Fetch 更加轻量级但也相对简单一些[^1]。
以下是相同逻辑下的 Fetch 版本实现方式:
```javascript
fetch('/users')
.then(response => response.json())
.then(data => this.users = data)
.catch(console.error);
function postUserData(userObj){
fetch("/add-user", {
method:"POST",
headers:{
"Content-Type":"application/json"
},
body:JSON.stringify(userObj),
})
.then(res=>res.json())
.then(()=>{ /* 更新UI */})
.catch(err=>console.warn("Error:", err));
}
```
尽管两者都能满足日常开发需求,但在大型复杂场景下推荐优先考虑 Axios 因为其灵活性更高且易于管理跨域等问题。
阅读全文
相关推荐


















