面试题答案
一键面试项目结构调整
- 创建
api
目录:在src
目录下创建api
目录,用于存放所有与后端接口交互的相关代码。 - 接口文件拆分:在
api
目录下,根据业务模块或功能,为不同的接口创建单独的js
文件。例如,用户相关接口放在user.js
,订单相关接口放在order.js
等。
Axios配置
- 安装Axios:如果项目还未安装Axios,在项目根目录下执行
npm install axios --save
。 - 创建Axios实例:在
src
目录下创建http.js
文件(可自行命名),用于配置Axios实例。
import axios from 'axios';
// 创建Axios实例
const service = axios.create({
// baseURL: process.env.VUE_APP_BASE_API, // 可以根据环境变量设置基础路径
timeout: 5000 // 请求超时时间
});
// 请求拦截器
service.interceptors.request.use(
config => {
// 在这里根据不同接口添加复杂的请求头
if (config.url.includes('/specificApi')) {
config.headers['Custom-Header'] = 'Some-Value';
}
return config;
},
error => {
return Promise.reject(error);
}
);
// 响应拦截器
service.interceptors.response.use(
response => {
return response.data;
},
error => {
return Promise.reject(error);
}
);
export default service;
不同跨域处理方式
- 代理方式:
- 在
vue.config.js
文件中配置代理。假设后端接口域名是http://api.example.com
,本地开发时通过代理解决跨域。
- 在
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://api.example.com',
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
}
}
};
- 在接口调用时,使用代理路径。例如:
import service from '@/http';
export function getUserInfo() {
return service.get('/api/user/info');
}
- 后端配合设置CORS方式:
- 对于后端设置CORS的接口,在Axios配置中不需要额外特殊处理代理相关配置。直接使用Axios实例进行请求。
import service from '@/http';
export function getOtherData() {
return service.get('http://another-api.com/data');
}
代码示例整合
user.js
接口文件示例:
import service from '@/http';
export function login(data) {
return service.post('/api/user/login', data);
}
export function getUserProfile() {
return service.get('/api/user/profile');
}
- 在Vue组件中使用:
<template>
<div>
<button @click="handleLogin">登录</button>
</div>
</template>
<script>
import { login } from '@/api/user';
export default {
methods: {
async handleLogin() {
try {
const response = await login({ username: 'test', password: '123456' });
console.log(response);
} catch (error) {
console.error('登录失败', error);
}
}
}
};
</script>
通过上述方式,可以在Vue项目中基于Axios优雅且灵活地处理复杂的跨域场景。