您好,登錄后才能下訂單哦!
本文實例講述了vue實現的請求服務器端API接口。分享給大家供大家參考,具體如下:
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程序設計有所幫助。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。