import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'//----
#通过use方法加载axios插件
Vue.use(VueAxios,axios)
this.$axios.get()
axios的引入方式二:
import Vue from 'vue'
import axios from 'axios'
使用Vue.prototype.$axios=axios
this.$axios.get()
https://blog.csdn.net/suwu150/article/details/78333452
-------qs.parse()、qs.stringify()使用方法
qs是一个npm仓库所管理的包,可通过npm install qs
命令进行安装.
1. qs.parse()将URL解析成对象的形式
const Qs = require('qs');
let url = 'method=query_sql_dataset_data&projectId=85&appToken=7d22e38e-5717-11e7-907b-a6006ad3dba0';
Qs.parse(url);
console.log(Qs.parse(url));
如上面代码所示,输出结果如下:
2. qs.stringify()将对象 序列化成URL的形式,以&进行拼接
const Qs = require('qs');
let obj= {
method: "query_sql_dataset_data",
projectId: "85",
appToken: "7d22e38e-5717-11e7-907b-a6006ad3dba0",
datasetId: " 12564701"
};
Qs.stringify(obj);
console.log(Qs.stringify(obj));
在这里需要注意的是,JSON中同样存在stringify方法,但是两者之间的区别是很明显的,如下所示:
{"uid":"cs11","pwd":"000000als","username":"cs11","password":"000000als"}
uid=cs11&pwd=000000als&username=cs11&password=000000als
如上所示,前者是采用JSON.stringify(param)进行处理,后者是采用Qs.stringify(param)进行处理的
进入正题:
1.新建http.js文件,封装axios get post 方法
import axios from 'axios'
import qs from 'qs'
import 'es6-promise'
axios.defaults.baseURL = '/api';
export function get(url, params) {
return new Promise((resolve, reject) => { axios.get(url, { params: params
}).then(res => { resolve(res.data)
}).catch(err => { reject(err) })
})
}
export function post(url, data) {
return new Promise((resolve, reject) => {
axios.post(url, qs.stringify(data), { headers: { 'Content-Type': 'application/x-www-form-urlencoded', }
} ).then(res => { resolve(res.data)
}).catch(err => { reject(err) })
})
}
2.建立api.js 封装接口
import {get, post} from './http'
export function getNewPublish() {
const result = get('/ad/newestPublishAdMaterialInfo1');
return result;
}
3.在组件中使用
import {getNewPublish} from '../../api/api'
let result = getNewPublish(); //这里面是可以有参数params
result.then(res => { console.log(res); }).catch(err => { console.log(err); })
4.加拦截器的封装
import axios from 'axios'
import qs from 'qs'
import {Toast} from 'antd-mobile'
axios.defaults.baseURL = '/api';
// 拦截请求
axios.interceptors.request.use(function (config) { Toast.loading('加载中', 0); return config });
// 拦截相应
axios.interceptors.response.use(function (config) { Toast.hide(); return config });
export default class Http {
static get(url, params) {
return new Promise((resolve, reject) => {
axios.get(url, { params: params
}).then(res => { resolve(res.data) }).catch(err => { reject(err) }) })
}
static post(url, params) {
return new Promise((resolve, reject) => {
axios.post(url, qs.stringify(params), { headers: { 'Content-Type': 'application/x-www-form-urlencoded', }
} ).then(res => { resolve(res.data) }).catch(err => { reject(err) }) })
} }
再来一个瞧瞧:
service文件夹下
config.js
const dev=process.env.NODE_ENV ==='development'
const paramError={msg:'参数错误'}
const serviceError={ msg:'服务器错误'}
const netError={ msg:'网络异常'}
const unknowError={ msg:'未知错误'}
let hostServer=''
if(dev){hostServer=`http://....../zztj-recruitment-external-webserver/rcrt`}else{
let host=window.location.host
hostServer=`http://${host}/zztj-recruitment-external-webserver/rcrt`
}
export{
hostServer,
paramError,
serviceError,
unknowError
}
index.js
import{hostServer,paramError,serviceError,unknowError}from './config'
import axios from 'axios'
//拦截器
axios.interceptor.request.use(config=>{
return config
},()=>{
return Promise.reject(paramError)
})
axios.interceptor.response.use(response=>{
if(response&&reponse.status>=200)&&response.status<300){
return response
}
return Pomise.reject(serviceError)
})
export default function ajax({url,data={},callback}){
const newUrl = `${hostServer}${url}`
const option={
method:'post'
headers:{
'ACCept':'application/json;charset=utf-8',
'Contenet-Type':'application/json'
}
}
return axios({url:newUrl,data,...option}).then(res=>{
if(typeof callback ==='function'){
callback&&callback()
}
if(res.responseCode==='10001'){
return Promise.resolve(res.data.data)
}
return Promise.resolve(res.data.data)
}).catch(error=>{
if(typeof callback==='function'){
callback &&callback(error)
}
common文件夹下的api文件夹
login.api.js
import ajax from '../../service'
export function getServerTime(){
return ajax({
url:'/onlineEvaluate/getServerTime'
})
export function sendMessageCode(data){
return ajax({
url:'/onlineEvaluate/getServerTime'
data
})
组件使用
getServerTime().then(res=>{
(return已经封装掉了) sendMessageCode({...}).then(res=>{})
})