1.request.js
1 import axios from 'axios'
2 import { Message } from 'element-ui';
3
4
5 const BASEURL = process.env.NODE_ENV === 'production' ? '' : '/devApi';
6 const instance = axios.create({
7 baseURL: BASEURL,
8 timeout: 15 * 1000, // 15s timeout
9
10 });
11
12
13 instance.interceptors.request.use(function (config) {
14 // 在发送请求之前做些什么
15 return config;
16 }, function (error) {
17 // 对请求错误做些什么
18 return Promise.reject(error);
19 });
20
21 // 添加响应拦截器
22 instance.interceptors.response.use(function (response) {
23 // 对响应数据做点什么
24 const data=response.data
25 if (data.resCode!=0){
26 Message.error(data.message)
27 return Promise.reject(data) //人为走catch代码
28 }
29 return response.data;
30 }, function (error) {
31 // 对响应错误做点什么
32 return Promise.reject(error);
33 });
34
35 export function get(url, params) {
36 return instance.get(url, {
37 params: params
38 })
39
40 }
41 export function post(url, params) {
42
43 instance.defaults.headers.post['Content-Type'] = 'application/json';
44 return instance.post(url, JSON.stringify(params))
45 }
2.api.js
1 import { get, post } from './request'
2
3
4 export function getSms(params) {
5 return post('/getSms/', params)
6 }
7 export function register(params){
8 return post('/register/',params)
9 }
10
11 export function login(params){
12 return post('/login/',params)
13 }
3.example
1 register(this.registerForm).then(data => {}).catch(e => { }); 4 5