<meta charset="utf-8">
安裝axios
npm install axios; // 安裝axios
封裝axios
在src文件夾中創(chuàng)建axios文件夾,再在axios文件夾中創(chuàng)建indx.js文件
在index.js文件中封裝
import axios from 'axios'
// 請(qǐng)求超時(shí)時(shí)間
axios.defaults.timeout = 30000000
axios.defaults.baseURL = process.env.NODE_ENV
axios.defaults.headers.post['Content-Type'] = 'application/json';
// axios 請(qǐng)求攔截器
axios.interceptors.request.use(
config => {
return config;
},
error => {
return Promise.error(error);
}
);
//ajax返回請(qǐng)求攔截 攔截
axios.interceptors.response.use(
response=> {
// ajax 返回狀態(tài)
const res = response.data
// 狀態(tài)不為200的時(shí)候
if (!res.features && res.code !== 200 ) {
return res
} else {
if (data.status) {
return res
} else {
if (!res.data) return 'null'
return res.data
}
}
},
error => {
const errMsg = error.toString()
const code = errMsg.substr(errMsg.indexOf('code') + 5)
if (parseInt(code) === 401) {
consloe.log(error)
}
return Promise.reject(error)
}
)
export default axios
在.env.development.js
和 .env.production
文件內(nèi)配置后臺(tái)接口的地址(區(qū)分生成環(huán)境和開(kāi)發(fā)環(huán)境)
// 項(xiàng)目的服務(wù)后臺(tái)接口的地址
module.exports = {
NODE_ENV = 'development'
VUE_APP_BASE_API = 'https://tmall-api.com/api'
}
在api文件夾下創(chuàng)建index.js文件
在index.js文件下輸入請(qǐng)求方式
import request from './axios'
// 引入后臺(tái)接口集合
export function getData(data) {
return request({
url: '/接口地址',
method: 'get',
params: data
})
}
最后在組件中引入就可以使用
import { getData } from '@/api/index'
getPageData() {
getData({
id: this.id,
keyword: this.keyword
}).then((res) => {
if(res.code == 200){
...
}else {
this.$message({
message: res.message,
type: 'warning'
})
}
})
}
自己開(kāi)發(fā)中的小心得寞宫,希望對(duì)大家有幫助