第三块 Vue的前置知识(下)

 

学习vue的前置知识


4. axios异步网络请求

AJAX = Asynchronous JavaScript and XML(异步的 JavaScript 和 XML)。

axios是封装了AJAX和大量使用promise的HTTP库,

4.1 axios简介

现在项目的两种编程方式-模板式编程(java-jsp、go-template…)和接口式编程(api)

简单来说:

模板式编程:替换占位符来相应数据

接口式编程:数据返回给 -> axios -> vue/react/… -> 展示

4.2 RestFul API规范

(URL,HTTP,版本,状态码,返回值,请求条件等规范)

GET (SELECT) :从服务器取出资源(一项或多项)

POST (CREATE):在服务器新建一个资源

PUT (UPDATE):在服务器更新资源(客户端提供改变后的完整资源)

PATCH (UPDATE):在服务器更新资源(客户端提供改变的属性

DELETE (DELETE) :从服务器删除资源

4.3 并发、并行、同步、异步、多线程的区别?

  • 并发:同一时间段有几个程序都处于已经启动到运行完毕之间,并且这几个程序都在同一个处理机上运行,并发的两种关系是同步和互斥;
  • 互斥:进程之间访问临界资源时相互排斥的现象;
  • 同步:进程之间存在依赖关系,一个进程结束的输出作为另一个进程的输入。具有同步关系的一组并发进程之间发送的信息称为消息或者事件;
  • 并行:单处理器中进程被交替执行,表现出一种并发的外部特征;在多处理器中,进程可以交替执行,还能重叠执行,实现并行处理,并行就是同事发生的多个并发事件,具有并发的含义,但并发不一定是并行,也就是说事件之间不一定要同一时刻发生;
  • 多线程:多线程是进程中并发运行的一段代码,能够实现线程之间的切换执行;
  • 异步:和同步相对,同步是顺序执行,而异步是彼此独立,在等待某个事件的过程中继续做自己的事,不要等待这一事件完成后再工作。线程是实现异步的一个方式,异步是让调用方法的主线程不需要同步等待另一个线程的完成,从而让主线程干其他事情。
  • 异步和多线程:不是同等关系,异步是目的,多线程只是实现异步的一个手段,实现异步可以采用多线程技术或者交给其他进程来处理。

4.4 axios

Get请求

<script>
    axios({
        method: "get",
        url: "http://api.k780.com",
        params: {
            app: 'weather.today',
            weaId: 1,
            appkey: "10003",
            sign: "b59bc3ef6191eb9f747dd4e83c99f2a4",
            format: "json",
        },
    }).then(res => {
        console.log(res);
    });
</script>

Post请求

<script>
    axios({
        method: "post",
        url: "http://api.k780.com",
        headers:{
            //表单
            'content-type':'application/x-www-form-urlencoded'
        },
        data: {
            app: 'weather.today',
            weaId: 1,
            appkey: "10003",
            sign: "b59bc3ef6191eb9f747dd4e83c99f2a4",
            format: "json",
        },
    }).then(res => {
        console.log(res);
    });
</script>

4.5 生产环境

安装环境

npm init -y
npm i webpack webpack-cil html-webpack-plugin -D

webpack.config.js

const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
	entry:"./src/index.js",//文件入口
	plugin:[
		new HtmlWebpackPlugin({
			template:"./src/index.html"
		})
	],
	mode:"development",
}

index.js

import axios from "axios";

axios.get("http://api.k780.com",{params: {
            app: 'weather.today',
            weaId: 1,
            appkey: "10003",
            sign: "b59bc3ef6191eb9f747dd4e83c99f2a4",
            format: "json",
        }}).then(res => {
        console.log(res);
    });

跨域

header: Access-Control-Allow-Origin

并发请求

//全部接收
axios.all([
    axios.get('http://api.k780.com/?app=weather.today&weaId=1&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json'),
    axios.get('http://api.k780.com/?app=weather.today&weaId=1&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json'),
    axios.get('http://api.k780.com/?app=weather.today&weaId=1&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json')
]).then(res=> {
    console.log(res);
}).catch(err => {
    consoLe.log(err);
})

//单个接收
axios.all([
    axios.get('http://api.k780.com/?app=weather.today&weaId=1&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json'),
    axios.get('http://api.k780.com/?app=weather.today&weaId=1&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json'),
    axios.get('http://api.k780.com/?app=weather.today&weaId=1&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json')
]).then(
    axios.spread((res1, res2, res3) => {
        console.log(res1);
        console.log(res2);
        console.log(res3);
})).catch(err => {
        consoLe.log(err);
})

4.6 全局配置

<script>
    axios.defaults.baseURL = "http://api.k780.com";
    axios.defaults.timeout = 3000;

    axios.get('?app=weather.today&weaId=1&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json').then(res => {
        console.log(res);
    }).catch(err => {
        console.log("--------error---------");
        console.log(err);
    })


    axios.post('link/add', "name=helloword&ur1=lmonkey&ord=5&do_submit=true").then(res => {
        console.log(res);
    }).catch(err => {
        console.log("--------error---------");
        console.log(err);
    })
</script>

4.6 实例封装

<script>
    
    let ap1_1 = axios.create({
        baseURL = "http://api.k780.com",
        timeout = 3000,
    })

    let ap1_2 = axios.create({
        baseURL = "http://api.k780.com",
        timeout = 4000,
    })

    ap1_1.get('?app=weather.today&weaId=1&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json').then(res => {
        console.log(res);
    }).catch(err => {
        console.log("--------error---------");
        console.log(err);
    })


    ap1_2.post('link/add', "name=helloword&ur1=lmonkey&ord=5&do_submit=true").then(res => {
        console.log(res);
    }).catch(err => {
        console.log("--------error---------");
        console.log(err);
    })

</script>

4.7 axios拦截器

请求拦截器

前端去请求后端时,拦截自己发送出去的请求

常见操作有:1.添加token 2.判断token的过期

<script>

    let ap1_1 = axios.create({
        baseURL = "http://api.k780.com",
        timeout = 3000,
    })

    ap1_1.interceptors.request.use(config=>{
        console.log("处理请求...");
        //继续执行
        return config;
    },err=>{
        console.log(err);
    })

    ap1_1.get('?app=weather.today&weaId=1&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json').then(res => {
        console.log(res);
    }).catch(err => {
        console.log("--------error---------");
        console.log(err);
    })

</script>

响应拦截器

后端返回数据给前端时,拦截返回过来的数据

常见操作:处理返回的状态码

<script>

    let ap1_1 = axios.create({
        baseURL = "http://api.k780.com",
        timeout = 3000,
    })

    ap1_1.interceptors.response.use(config => {
        console.log("处理响应...");
        //处理响应码
        if (response.status == 200) {
            //只放行返回来的数据
            return config.data;
        }
    }, err => {
        console.log(err);
    })

    ap1_1.get('?app=weather.today&weaId=1&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json').then(res => {
        console.log(res);
    }).catch(err => {
        console.log("--------error---------");
        console.log(err);
    })

</script>

参考资料

并发、并行、同步、异步、多线程的区别?