十一、网络请求
一、axios基本属性和设置
安装
1 npm i -S axios
axios支持的请求方式
- get
- post
- put:修改数据
- delete:删除数据
axios响应结果的属性
- config:配置信息
- data:实际响应的数据
- headers:响应头信息
- status:响应状态码
- statusText:响应状态信息
axios请求配置
1 // 设置根路径地址 2 axios.defaults.baseURL = 'https://api.example.com';
1 // 设置超时时间 2 axios.defaults.timeout = 3000;
1 // 设置请求头 2 axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
二、axios封装
1 import axios form 'axios' 2 3 export function request(config) { 4 // 1、创建axios实例 5 const instance1 = axios.create({ 6 baseUrl: 'http://www.baidu.com', 7 timeout: 5000 8 // headers: {'X-Custom-Header': 'foobar'} 9 }) 10 11 // 2.1、axios拦截器——请求拦截 12 instance1.interceptors.request.use(config => { 13 // 1.比如config中一些信息不符合服务器要求,需要修改 14 15 // 2.比如每次发送网络请求时,希望在界面添加一个loading加载的图标 16 17 // 3.某些网络请求(比如登录(需要携带token),携带一定信息) 18 19 return config 20 }, err => { 21 console.log(err) 22 }) 23 24 // 2.2、axios拦截器——响应拦截 25 instance1.interceptors.response.use(res => { 26 // 处理响应数据 27 return res.data 28 }, err => { 29 console.log(err) 30 }) 31 32 // 3、发送真正的网络请求 33 return instance1(config) 34 }
1 import { request } from './request' 2 3 export function getHomeMultidata () { 4 return request({ 5 url: '/home/mulitdata' 6 }) 7 } 8 9 export function getHomeGoods (type, page) { 10 return request({ 11 url: '/home/mulitdata', 12 params: { 13 type, 14 page 15 } 16 }) 17 }
组件内调用
1 getHomeMultidata () { 2 getHomeMultidata().then(res => { 3 this.banners = res.data.banner.list 4 }) 5 }, 6 getHomeGoods (type) { 7 const page = this.goods[type].page + 1 8 getHomeGoods(type, page).then(res => { 9 this.goods[type].list.push(...res.data.list) 10 this.goods[type].page += 1 11 }) 12 }
三、mock数据
1 { 2 "msg": "success", 3 "code": 0, 4 "data": [ 5 { 6 "id": 1, 7 "img": "https://storage.lynnn.cn/assets/markdown/91147/pictures/2020/11/bce52a5f143cd3e25c6c39c7a0fd7f276ce43bad.png?sign=f4ec5771f7eabd11226fe5f4b7f0f6e8&t=5fa403f2", 8 "title": "第1张图片" 9 }, 10 { 11 "id": 2, 12 "img": "https://storage.lynnn.cn/assets/markdown/91147/pictures/2020/11/6018ac895dd29437b1d023c121c7539ecf2e9221.jpeg?sign=47da092f8a6a1650df3da3dd3dd40cb3&t=5fa4041d", 13 "title": "第2张图片" 14 }, 15 { 16 "id": 3, 17 "img": "https://storage.lynnn.cn/assets/markdown/91147/pictures/2020/11/f81d133833b89a18cb1842f449810d16ec5d3c78.jpeg?sign=22eadb72caac161df642aa18b84127a8&t=5fa40431", 18 "title": "第3张图片" 19 }] 20 }
1 npm i -g json-server
3、配置mock:有多个json文件
-
创建
public/mock/mock.js
文件(文件名并非固定)
1 // json-server配置文件(commonJs模块化) 2 const swiper = require("./cb-swiper.json"); 3 4 // 导出 5 module.exports = () => ({ 6 swiper, 7 });
1 { 2 "/api/swiper": "/swiper" 3 }
- 在package.json文件中的scripts中配置启动命令
- 启动web服务
1 npm run mock