使用
- api.js中引入request.js
import request from '@/utils/request'
//vue
export function get(data) {
return request({
url: 'api/manifest',
method: 'get',
params: data
})
}
export function add(data) {
return request({
url: 'api/manifest',
method: 'post',
data
})
}
}
- 页面中引入api.js
import { add } from '@/api/api.js'
methods:{
async getData(){
var res=await add({xxx:xxx})
}
}
1.vue 版本 request.js
import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/authCookies'
import { getTokenStorage, setTokenStorage } from '@/utils/authLocalStorage'
const service = axios.create({
baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
timeout: 5000 // request timeout
})
// request interceptor
service.interceptors.request.use(
config => {
// do something before request is sent
if (store.getters.token) {
// let each request carry token
// ['X-Token'] is a custom headers key
// please modify it according to the actual situation
// 使用cookies
config.headers['X-Token'] = getToken()
// 使用localStorage
// config.headers['Authorization'] = getTokenStorage()
}
return config
},
error => {
// do something with request error
console.log(error) // for debug
return Promise.reject(error)
}
)
// response interceptor
service.interceptors.response.use(
response => {
const res = response.data
//查看响应中是否有验证,不一样就更新
// if the custom code is not 20000, it is judged as an error.
if (res.code !== 20000) {
Message({
message: res.message || 'Error',
type: 'error',
duration: 5 * 1000
})
// 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
// to re-login
MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
confirmButtonText: 'Re-Login',
cancelButtonText: 'Cancel',
type: 'warning'
}).then(() => {
store.dispatch('user/resetToken').then(() => {
location.reload()
})
})
}
return Promise.reject(new Error(res.message || 'Error'))
} else {
return res
}
},
error => {
console.log('err' + error) // for debug
Message({
message: error.message,
type: 'error',
duration: 5 * 1000
})
return Promise.reject(error)
}
)
export default service
2. 原生微信小程序 的 request.js
// request.js
const request = options => {
return new Promise((resolve, reject) => {
const {
data,
method
} = options
// const data=options.data
// const method=options.method
if (data && method !== 'get') {
options.data = JSON.stringify(data)
}
var headers = {}
if (wx.getStorageSync('token')) {
headers = {
'X-Atayun-Token': wx.getStorageSync('token')
}
}
//请求
wx.request({
header: {
'Content-Type': 'application/json',
...headers
},
// ...options,
success: function (res) {
if (res.data.code === 0 ) {
resolve(res.data)
} else {
wx.showToast({
title: 'fail:'+res.data.msg,
icon: 'none',
duration: 2000
})
reject(res.data)
}
},
fail: function (res) {
reject(res.data)
}
})
})
}
export default request