数据请求相关(json-server、postman、axios

2022-12-11  本文已影响0人  squidbrother

概述
json-server : 一个快速开发的服务器,testful风格的接口,数据可以在对应文件内编辑
postman : 模拟数据,请求接口
网络基础相关
axios : 数据请求的包,拥有好用的请求拦截器,响应拦截器

json-server (快速建立一个服务器,并将数据放在一个json文件内)

  1. 安装: 全局安装即可
npm install json-server -g
  1. 使用:指定文件夹内执行
json-server xxx.json   //没有xxx.json,则创建并打开,有则打开
  1. 手动修改数据结构
    使用sublime或记事本打开 xxx.json,手动编辑即可,如同操作json数据结构一样

  2. 一些特性与问题

postman (请求服务器接口的客户端)

  1. 安装:
    前往官网(www.postman.com),下载PC系统对应的安装文件(Download the desktop app)

  2. 使用:

网络基础相关

网络请求的三个组成部分( 请求行、请求头 、请求体 )

  1. 请求行 (method url)

  2. 请求头

  1. 请求体
  1. 常见状态码
状态码 英文描述 中文描述
200 OK 请求成功
201 Created 已创建,成功请求并创建了新的资源
401 Unauthorized 未授权/请求要求用户的身份认证
404 Not Found 服务器无法根据客户端找到资源
500 Internal Server Error 服务器内部错误
  1. API分类
  2. restful 风格
  1. restless 风格

axios (数据请求第三方包)

※ 安装:
通过npm安装 npm install axios -S 或者 通过CDN引用远程地址

※ 使用:

  1. 简写方式
axios.get('http://localhost:3000/students/16').then(response=>{
    console.log(response.data.name);
},error=>{
    console.log(error);
});
axios.post('http://localhost:3000/students/',{name:'小乐'}).then(response=>{
    console.log(response.data.name);
},error=>{
    console.log(error);
});
  1. post 请求体的两种书写方式
    第1种,携带请求体参数 (application/json编码) -- data: { name:zhangsan, age:18 }
    第2种,携带请求体参数 (application/x-www-form-urlencoded编码) -- data:'name=zhangsan&age=18'
axios({
    url: 'http://localhost:3000/students'
    method: 'POST',
    data: { name:zhangsan, age:18 }
.then(
    response => { console.log( 成了 ,response.data); },
    error => { console.log( 失败了 ,error); }
);
  1. 请求拦截器
//结构一个可以实例出某个取消请求的构造函数
const { CancelToken } = axios;
//定义一个取消某个定时器的函数
let _axiosCancelFn = null;
//拦截器中配置取消的方法 - (全局统一配置)
axios.interceptors.request.use(function(config){
    //一个请求节流器
        //如果在这里做请求节流,那么axios.all永远不会完成执行(不建议此处写节流)
    if(_axiosCancelFn){
        //给变量 _axiosCancelFn 赋值,对应这次axios请求的取消函数
        //这个取消函数,接收一个字符串参数,用来说明取消原因; _axiosCancelFn('单纯的不想请求数据了');
        _axiosCancelFn('单纯的不想请求数据了'); 
    };
    config.cancelToken = new CancelToken((c)=>{
        _axiosCancelFn = c;
    });
    return config;
});
  1. 响应拦截器
const { CancelToken,isCancel } = axios;

//响应拦截器
axios.interceptors.response.use(
    (response) => { return response; },
    (error) => {
        //查看是否为人为取消请求
        if(isCancel(error)){
            console.log('请求失败:',error.message);
        }else{
            console.log('请求失败:',error);
        };
        //停止axios请求中的error流程
        return new Promise(()=>{});
    }
);
  1. axios的批量请求 - axios.all
//批量请求
;(async function(){
    try{
        //以为axios.all的特性,要等所有结果都回来才行,如果在请求拦截器,通过CancelToken的取消方法做防抖,那么除了最后一项会执行完毕,都会失败,这样这个.all函数永远不会有执行结果。
        //请求了~~~~~~~~~~~~~~              触发了3次
        //请求失败: 单纯的不想请求数据了     触发了2次
        axios.all([
            axios.get('http://localhost:3000/students/11'),
            axios.get('http://localhost:3000/students/14'),
            axios.get('http://localhost:3000/students/15')
        ]).then(
            (response)=>{
                response.forEach(item => {
                    console.log(item.data.name);
                });
            },
            (error)=>{
                console.log(error);
            }
        );
    }catch(err){
        console.log(err);
    };
})();
  1. axios的请求配置 - 全局配置
axios.defaults.baseURL = 'http://xxxxx';
axios.default.timeout = 2000;
axios.defaults.headers= { token:' xxxxxx ' };
  1. axios创建克隆体 - 局部配置
//axios2为克隆体
const axios2 = axios.create({
    timeout: 3000,
    baseURL:'http://xxxxx'
})
  1. 请求操作中通过async和await实现更加优雅的写法

※ 关于async

//快速获取某学生信息
_btn4.onclick = async function(){
    try{
        var _resData = await axios.get('/students/16');
        console.log(_resData.data.name);
    }catch(err){
        console.log(err);
    };
};
上一篇 下一篇

猜你喜欢

热点阅读