VUE- 访问服务器端数据 axios
一,安装
npm install axios
二,在http.js中引入
import axios from 'axios';
三,定义http request 拦截器,添加数据请求公用信息
axios.interceptors.request.use( config => { // const token = getCookie('名称');注意使用的时候需要引入cookie方法,推荐js-cookie //config.data = JSON.stringify(config.data); let token = localStorage.token; //let token = 'xxx'; let appid = 'xxx'; let appID = decodeURIComponent(appid); config.headers.token = token; //config.headers['Content-Type'] = 'application/x-www-form-urlencoded'; if (config.method == 'get') { config.params.app_id = appID config.params.token = token } if (config.method == 'post') { config.data.token = token config.data.app_id = appID } return config; }, error => { return Promise.reject(err); } );
四,封装get方法
export function get(url, params = {}) { return new Promise((resolve, reject) => { axios.get(url, { params: params }) .then(response => { resolve(response.data); }) .catch(err => { reject(err) }) }) }
五,封装post方法
export function post(url, params = {}) { return new Promise((resolve, reject) => { axios.post(url, params) .then(response => { resolve(response.data); }, err => { reject(err) }) }) }
六,封装patch请求
export function patch(url, data = {}) { return new Promise((resolve, reject) => { axios.patch(url, data) .then(response => { resolve(response.data); }, err => { reject(err) }) }) }
七,封装put请求
export function put(url, data = {}) { return new Promise((resolve, reject) => { axios.put(url, data) .then(response => { resolve(response.data); }, err => { reject(err) }) }) }
八,实现跨域
const downloadUrl = url => { let iframe = document.createElement('iframe') iframe.style.display = 'none' iframe.src = url iframe.onload = function() { document.body.removeChild(iframe) } document.body.appendChild(iframe) }
九,方法的使用
在main.js里引入http.js
import Vue from 'vue' import App from './App' import router from './router' import axios from 'axios' import {get, post } from '@/utils/http' Vue.prototype.$ajax = axios; Vue.prototype.$post = post; Vue.prototype.$get = get;
在需要调用的地方,参考:https://www.cnblogs.com/1285026182YUAN/p/11393522.html
this.$get(url).then((response) => { } })
this.$post(url, data).then((response) => { } })
this.$put(url, data).then((response) => { } })
this.$patch(url, data).then((response) => { } })