axios在vue项目中的一种封装方法

记录下之前领导封装的axios请求

npm install axios // 安装

单独写个文件配置axios,此处为request.js

 1 import axios from 'axios'
 2 
 3 //自定义配置新建一个axios实例
 4 const http = axios.create({
 5     // baseURL: 'https://...' 
 6     // baseURL: process.env.BASE_API,
 7     timeout: 5000, //
 8     // headers: {'x-Request-with': '*'}//自定义请求头
 9     // ....
10 })
11 // 添加请求拦截器
12 http.interceptors.request.use(config => {
13     // 请求前设置请求头
14     config.headers['Access-Control-Allow-Origin'] = '*'
15       // config.headers['Authorization'] = getToken()
16       // config.headers['Actcode'] = getCode()
17       return config
18 },error => {
19     console.log(error, '888')//请求错误 do something
20     return Promise.reject(error)
21 })
22 // 响应拦截器
23 http.interceptors.response.use(response => {
24     return response
25 }, error => {
26     console.log(error, '888')//返回消息后 do something
27     return Promise.reject(error)
28 })
29 export default http  // 记住此处
30 // axios 依赖原生的 ES6 Promise
32 // 低版本浏览器不支持es6语法,使用垫片
33 // import promise from 'es6-promise' 需安装
34 // promise.polyfill()

然后api.js 配置请求时的方法

 1 import http from '@/http/request'
 2 
 3 export function yiyuan (showapi_appid, showapi_sign) { //方法名 yiyuan
 4     const pass = {showapi_appid, showapi_sign}
 5     return http({
 6         url: 'http://route.showapi.com/60-27',
 7         method: 'post',
 8         data: pass
 9     })
10 }

页面中使用的时候直接 引入方法

import {yiyuan} from '@/api' 
使用:
let pass = {}
yiyuan(pass).then().catch()

够不够简单(#手动滑稽#)