1、 在 src 目录下创建 utils 目录及 utils 下面创建 request.js 文件
在pubilc中创建一个db.json文件
内容如下:
import axios from 'axios'
// 手动创建一个 axios 对象, 参考:https://github.com/axios/axios#creating-an-instance
const request = axios.create({
// 请求配置参考: https://github.com/axios/axios#request-config
// 根据不同环境设置 baseURL, 最终发送请求时的URL为: baseURL + 发送请求时写URL ,
// 比如 get('/test'), 最终发送请求是: /dev-api/test
// baseURL: '/dev-api',
baseURL: '/',
timeout: 5000 // 请求超时
})
//添加拦截器
//请求拦截
request.interceptors.request.use(config=>{
//在发送请求之前做的事
return config
},error=>{
//请求错误做的事
return Promise.reject(error)
})
//响应拦截
request.interceptors.response.use(response=>{
//响应成功之前做的事
return response
},error=>{
//响应失败之后做的事
return Promise.reject(error)
})
export default request// 导出 axios 对象
2、在src下创建一个api文件夹,api中创建一个test.js文件
test.js文件内容如下:
import request from "../utils/request"//导入request文件
//默认路径
const BASE_URL="http://localhost:8888/"
//请求方式1
request.get(BASE_URL+"db.json").then(res=>{
console.log(res)
}).catch(error=>{
console.log(error)
})
//请求方式2
request({
type:'get',
url:BASE_URL+'db.json'
}).then(res=>{
console.log(res)
}).catch(error=>{
console.log(error)
})
export default {
getList(){
return request({
type:'get',
url:BASE_URL+'db.json'
})
}
}
3、在组件中使用
//先引入
import test from "../api/test"
//在生命周期中调用使用
created(){
this.fetch()
},
methods:{
frtch(){
test.getList(),then(res=>{
console.log(res)
}).catch(error=>{
console.log(error)
})
}
}