一、axios基础
0 官网
axios官网
1 安装
1
| npm install axios --save
|
- 注意:项目名称不能与axios同名 否则不能成功安装
2 特性
3 vue中使用axios
主要讲封装的内容
目录
- 在src目录下新建
utils/resques.js
3.1 封装与使用
封装
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| import axios from 'axios'
export const post = (url, data = {}) => { return new Promise((resolve, reject) => { axios.post(url, data, { baseURL: 'https://www.fastmock.site/mock/ae8e9031947a302fed5f92425995aa19/jd', headers: { 'Content-Type': 'application/json' } }).then(res => { console.log(res) resolve(res.data) }, err => { reject(err) }) }) }
|
使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| <script> import { post } from '../../utils/request' export default { name: 'Login', setup () { const handleLogin = () => { post('/api/user/login', { username: 'username1', password: 'password1' }).then(() => { alert('成功') }).catch(() => { alert('失败') }) } } } </script>
|
3.2 配置默认值
配置默认值官网文档
1 2 3 4 5 6
| axios.defaults.baseURL = 'https://api.example.com'; axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
axios.get('/colums').then((res) => {....})
|
1 2 3 4 5 6 7
| const instance = axios.create({ baseURL: 'https://api.example.com' });
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
|
3.3 拦截器
拦截器官网
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
|
axios.defaults.baseURL = 'http://apis.imooc.com/api/' axios.interceptors.request.use( config =>{ config.params = { ... config.params, icode: 'C6A6C4086133360B'} return config }) axios.get( '/columns' ).then( resp => { console.log(resp.data) })
axios.interceptors.request.use(config => { store.commit('setLogin', true) return config }) axios.interceptors.response.use(config => { store.commit('setLogin', false) return config })
|
3.2 实例化axios
创建实例官网文档
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
| import axios from 'axios'
const instance = axios.create({ baseURL: 'https://www.fastmock.site/mock/ae8e9031947a302fed5f92425995aa19/jd', timeout: 10000 })
export const get = (url, params = {}) => { return new Promise((resolve, reject) => { instance.get(url, { params }).then(res => { console.log(res) resolve(res.data) }, err => { reject(err) }) }) }
export const post = (url, data = {}) => { return new Promise((resolve, reject) => { instance.post(url, data, { headers: { 'Content-Type': 'application/json' } }).then(res => { console.log(res) resolve(res.data) }, err => { reject(err) }) }) }
|
3.3 带参url
3.3.1 get
1
| /api/shop/:id/products?tab=all
|
1 2 3
| const res = await get(`/api/shop/${shopId}/products`, { tab: currentTab.value })
|
1 2 3
| const res = await get(`/api/shop/${shopId}/products`, { tab: currentTab.value })
|
二、fetch
https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch
https://www.ruanyifeng.com/blog/2020/12/fetch-tutorial.html
https://blog.csdn.net/qq_53225741/article/details/125239106