1、安裝axios
npm install axios
2钠龙、引入axios
import axios from 'axios'
import Qs from 'qs'
3蝗拿、定義request.js
// create an axios instance
const service = axios.create({
baseURL: process.env.BASE_API, // api的base_url
timeout: 5000 // request timeout
})
// 設(shè)置請(qǐng)求攔截器
service.interceptors.request.use(config => {
// 參數(shù)轉(zhuǎn)換為表單模式
if (config.data) {
config.data = Qs.stringify(config.data)
}
// 設(shè)置請(qǐng)求頭
config.headers = {
'Content-Type': 'application/x-www-form-urlencoded', // 模擬form表單方式提交請(qǐng)求
'Access-Token': store.getters.token === undefined ? '' : store.getters.token() // 設(shè)置token
}
return config
}, error => {
console.log(error) // for debug
Promise.reject(error)
})
// 設(shè)置響應(yīng)攔截器
service.interceptors.response.use(
response => response,
error => {
console.log('err' + error) // for debug
Message({
message: error.message,
type: 'error',
duration: 5 * 1000
})
return Promise.reject(error)
})
export default service
4、使用
import request from 'request'
export function fetchList(query) {
return request({
url: '/article/list',
method: 'get',
data: query
})
}
import { fetchList } from '@/api/article'
methods: {
getList() {
this.listLoading = true
fetchList(this.listQuery).then(response => {
this.list = response.data.items
this.total = response.data.total
this.listLoading = false
})
}
}