Axios
axios.creat([config])
我们应该会遇到这样一个问题,就是使用多个 axios,需要配置 url,header,type 等等,那么我们多给请求就会面临写多个配置,看下面我们是怎么来解决他。
创建一个新的 axios
1 2 3 4 5
| var instance = axios.create({ baseURL: 'https://s-domain.com/api/', timeout: 1000, headers: {'X-Custom-Header': 'foobar'} });
|
使用 instance 发请求 一共有两种方式
1 2 3 4 5 6 7 8 9 10
|
instance({ url: '/posts' })
instance.get('/posts')
|
多个地址请求
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| baseURL1:https: baseURL2:https: baseURL3:https:
const baseURL1=https: const baseURL2=https: const baseURL3=https:
var instance1 = axios.create({ baseURL: baseURL1, timeout: 1000, headers: {'X-Custom-Header': 'foobar'} });
var baseURL2= axios.create({ baseURL: baseURL1, timeout: 1000, headers: {'X-Custom-Header': 'foobar'} });
var baseURL3= axios.create({ baseURL: baseURL1, timeout: 1000, headers: {'X-Custom-Header': 'foobar'} });
|
Demo
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| <script src="https://unpkg.com/axios/dist/axios.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <div> <button @click="clickmock">axios请求</button> </div>
<script type="text/javascript">
const instance = axios.create({ baseURL: 'https://tmawx.shenzhenair.com/ShInterfaceCenterV4/travelsky/', timeout: 1000, headers: { 'Content-Type': 'text/plain;charset=UTF-8' } });
const vue = new Vue({ el: '#app', data: { }, methods: { clickmock() {
console.log('点击请求')
instance({ method: 'post', url: 'consumer/trace/passengerTraceClient/getTripFlight', data: { openId: "oEy5O1231312321315sk", userId: "2597123134300" } }).then(res => { console.log(res); }).catch(err => { console.log(err); }) } }
})
|