本文實例講述了vue實現(xiàn)的請求服務器端API接口。分享給大家供大家參考,具體如下:
十載的府谷網站建設經驗,針對設計、前端、開發(fā)、售后、文案、推廣等六對一服務,響應快,48小時及時工作處理。全網營銷推廣的優(yōu)勢是能夠根據用戶設備顯示端的尺寸不同,自動調整府谷建站的顯示方式,使網站能夠適用不同顯示終端,在瀏覽器中調整網站的寬度,無論在任何一種瀏覽器上瀏覽網站,都能展現(xiàn)優(yōu)雅布局與設計,從而大程度地提升瀏覽體驗。成都創(chuàng)新互聯(lián)公司從事“府谷網站設計”,“府谷網站推廣”以來,每個客戶項目都認真落實執(zhí)行。
import axios from 'axios' import router from '@/router' axios.defaults.timeout = 3000 axios.defaults.baseURL = '' axios.interceptors.request.use( config => { // const token = getCookie('名稱') config.data = config.data config.headers = { 'Content-Type': 'application/json; charset=utf-8' } if (config.url === '/api/login/index') { } else { 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, Box }, 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程序設計有所幫助。