使用
- api.js中引入request.js
区别:
vue
中使用的axios,get
用params
,post
使用data
uniapp
中get
和post
都可以使用data
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
})
}
// uniapp
export function get(data) {
return request({
url: 'api/manifest',
method: 'get',
data
})
}
export function add(data) {
return request({
url: 'api/manifest',
method: 'get',
data
})
}
- 页面中引入api.js
import { add } from '@/api/api.js'
methods:{
async getData(){
var res=await add({xxx:xxx})
}
}
1. uniapp版本 request.js
import _config from './config'; // 导入私有配置
export default function $http(options) {
// 进行url字符串拼接,_config.url是再config中配置要请求的域名或者id+端口号这样方便管理,
// options.url是index中请求配置的
options.url = _config.url + options.url;
let timeStramp = Math.round(new Date().getTime() / 1000).toString();
var op = {
timeStramp
}
options.data = Object.assign(options.data, op)
return new Promise((resolve, reject) => {
_config.header = options.method === 'get' ? {
"Content-Type": "application/json; charset=UTF-8"
} : {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
};
// 请求头携带token
let token = uni.getStorageSync('token')
if (token) {
_config.header['Authorization'] = token;
}
// 显示加载中 效果
uni.showLoading({
title: "加载中",
mask: true
});
_config.complete = (response) => {
setTimeout(() => {
uni.hideLoading();
}, 100);
// 登录失效
if (response.data.code === "401") {
//返回登录界面
console.log('登录失效');
uni.showModal({
title: '未登录',
content: '您未登录,需要登录后才能继续',
showCancel: false,
success: (res) => {
/**
* 如果需要强制登录,使用reLaunch方式,并且移除token
*/
uni.reLaunch({
url: '/pages/login/index'
});
// store.dispatch('user/removeToken')
}
})
} else if (response.data.code === 200) {
resolve(response.data);
} else {
uni.showModal({
title: '提示',
content: response.data.msg,
showCancel: false,
success: res => {
}
});
reject(response.data);
}
}
_config.fail = (response) => {
uni.showToast({
icon: 'none',
title: '系统异常,请稍后再试'
});
}
// 开始请求
uni.request(Object.assign({}, _config, options));
})
}
2.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
3. 原生微信小程序 的 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