1、在src目录下创建http文件夹,在http文件夹下分别创建index.js、request.js、api.js
2、index.js的作用:用于导出api.js定义的所有接口,代码如下
export * from './api' ;
3、request.js代码如下:
import axios from 'axios' ;
import buildURL from 'axios/lib/helpers/buildURL' ;
import { merge } from 'axios/lib/utils' ;
function isPlainObject ( val ) {
return val && val. constructor. name === 'Object'
}
let requestInterceptors = [
config => {
config. headers. authorization = sessionStorage. getItem ( 'Token' ) ;
if ( config. emulateJSON && isPlainObject ( config. data) ) {
config. data = buildURL ( '' , config. data) . substr ( 1 ) ;
}
return config;
}
]
let responseInterceptors = [
res => {
return Promise. resolve ( res) ;
} ,
err => {
return Promise. reject ( err) ;
}
]
let serviceCreate = config => {
let service = axios. create ( merge ( { } , config) ) ;
service. interceptors. request. use ( ... requestInterceptors) ;
service. interceptors. response. use ( ... responseInterceptors) ;
return service
}
serviceCreate ( ) ;
export { serviceCreate, merge } ;
4、api.js代码如下:
import { serviceCreate, merge } from '@/http/request' ;
let http0 = serviceCreate ( {
baseURL : '/project1/api1' ,
timeout : 15000 ,
emulateJSON : true ,
} )
let http1 = serviceCreate ( {
baseURL : '/project2/api2' ,
timeout : 15000 ,
emulateJSON : true ,
} )
export function getData ( params, config ) {
return http0. get ( '/project/list' , merge ( config, { params } ) ) ;
}
export function deleteData ( params, config ) {
return http0. delete ( '/project/list' , merge ( config, { params } ) ) ;
}
export function postDataFrom ( params, config ) {
return http0. post ( '/project/list' , params, config) ;
}
export function postDataJson ( params, config ) {
return http0. post ( '/project/list' , params, merge ( config, { emulateJSON : false } ) ) ;
}
export function putDataFrom ( params, config ) {
return http0. put ( '/project/list' , params, config) ;
}
export function putDataJson ( params, config ) {
return http0. put ( '/project/list' , params, merge ( config, { emulateJSON : false } ) ) ;
}
5、页面中调用
import { getData, deleteData, postDataFrom, postDataJson, putDataFrom, putDataJson } from "@/http" ;
getData ( { name : "我是参数" } ) . then ( res => { console. log ( "返回数据" , res) } )
deleteData ( { name : "我是参数" } ) . then ( res => { console. log ( "返回数据" , res) } )
postDataFrom ( { name : "我是参数" } ) . then ( res => { console. log ( "返回数据" , res) } )
postDataJson ( { name : "我是参数" } ) . then ( res => { console. log ( "返回数据" , res) } )
putDataFrom ( { name : "我是参数" } ) . then ( res => { console. log ( "返回数据" , res) } )
putDataJson ( { name : "我是参数" } ) . then ( res => { console. log ( "返回数据" , res) } )