微信小程序即然来啦_vue完成的请求效劳器端API接

2021-01-07 13:31 jianzhan
vue实现的请求服务器端API接口示例       这篇文章主要介绍了vue实现的请求服务器端API接口,结合实例形式分析了vue针对post、get、patch、put等请求的封装与调用相关操作技巧,需要的朋友可以参考下
if (localStorage.getItem('Authorization')) { config.headers.Authorizatior = localStorage.getItem('Authorization') // if (token) { // config.params = {'token': token} // } return config error = { return Promise.reject(error) axios.interceptors.response.use( response = { //返回错误跳转到首页 if (response.data.code === 0) { router.push({ path: '/', querry: { redirect: router.currentRoute.fullPath return response error = { if (error.response) { switch (error.response.status) { case 401: localStorage.removeItem('Authorization') router.push('/login') return Promise.reject(error) * 封装get方法 * @param url * @param data * @returns {Promise} export function fetch (url, params = {}) { return new Promise((resolve, reject) = { axios.get(url, { params: params .then(response = { resolve(response.data) .catch(err = { reject(err) * 封装post请求 * @param url * @param data * @returns {Promise} export function post (url, data = {}) { return new Promise((resolve, reject) = { axios.post(url, data) .then(response = { resolve(response.data) }, err = { reject(err) * 封装patch请求 * @param url * @param data * @returns {Promise} export function patch (url, data = {}) { return new Promise((resolve, reject) = { axios.patch(url, data) .then(response = { resolve(response.data) }, err = { reject(err) * 封装put请求 * @param url * @param data * @returns {Promise} export function put (url, data = {}) { return new Promise((resolve, reject) = { axios.put(url, data) .then(response = { resolve(response.data) }, err = { reject(err)

main.js调用

import { fetch, post, patch, put } from '@/util/fetch'
Vue.prototype.get = fetch
Vue.prototype.post = post
Vue.prototype.patch = patch
Vue.prototype.put = put

视图页面使用 

export default {
 name: 'login',
 data () {
 return {
 mobile: '',
 password: ''
 components: {
 XInput,
 XButton,
 Group,
 methods: {
 handleLogin () {
 let params = {}
 params.username = this.mobile
 params.password = this.password
 this.post('/api/driver/index', params).then((data) = {
 console.log(data)
 }).catch((error) = {
 console.log(error)

希望本文所述对大家vue.js程序设计有所帮助。