axios

一、搭建服务器

学习axios需要有响应的后台服务器,配合axios发的请求。所以,这里使用json server搭建一个简单的服务器。

1.下载json server

npm install -g json-server

2.创建文件

如创建一个db.json文件:

{
  "posts": [
    {
      "id": 1,
      "title": "json-server",
      "author": "typicode"
    },
    {
      "id": 2,
      "title": "横渠四句",
      "author": "为往圣继绝学,为万世开太平"
    },
    {
      "title": "横渠四句",
      "author": "----",
      "id": 3
    },
    {
      "title": "林则徐",
      "author": "苟利国家生死以,岂因祸福避趋之",
      "id": 4
    }
  ],
  "comments": [
    {
      "id": 1,
      "body": "some comment",
      "postId": 1
    }
  ],
  "profile": {
    "name": "typicode"
  }
}

3.启动json server

json-server --watch db.json

这句命令的意思是,启动json-server,去db.json中去找数据。

如果出错了使用 npx json-server --watch db.json启动

二、使用axios

引入axios,一般项目中都是npm i axios下载再使用,这里就直接通过src引入了。

<script src="https://cdn.staticfile.org/axios/0.18.0/axios.min.js"></script>

(1)、发送请求对数据增删改查

    <button class="btn1">get请求</button>
    <button class="btn2">post请求</button>
    <button class="btn3">delete请求</button>
    <button class="btn4">put请求</button>
    
    <script>
        // 查
        var btn = document.getElementsByTagName("button")
        btn[0].onclick = function(){
            axios({
                method:'get',
                //查看id为1的数据
                url:'http://localhost:3000/posts/1'
            }).then(Response=>{
                console.log(Response)
            })
        }
        

        //增
        var btn = document.getElementsByTagName("button")
        btn[1].onclick = function(){
            axios({
                method:'post',
                url:'http://localhost:3000/posts',
                data:{
                    "title": "横渠四句",
                    "author": "为天地立心,为生民立命"
                }
            }).then(Response=>{
                console.log(Response)
            })
        }

        // 删
        var btn = document.getElementsByTagName("button")
        btn[2].onclick = function(){
            axios({
                method:'delete',
                //删除id为3的一条数据
                url:'http://localhost:3000/posts/3',
            }).then(Response=>{
                console.log(Response)
            })
        }

        // 改
        var btn = document.getElementsByTagName("button")
        btn[3].onclick = function(){
            axios({
                method:'put',
                //修改id为2的数据
                url:'http://localhost:3000/posts/2',//url大写会报错
                data:{
                    "id": 2,
                    "title": "横渠四句",
                    "author": "为往圣继绝学,为万世开太平"
                }
            }).then(Response=>{
                console.log(Response)
            })
        }
        

(2)、通过axios的一些方法发送ajax请求

        // 发送get请求
        var btn = document.getElementsByTagName("button")
        btn[0].onclick = function(){
            axios.request({
                method:'get',
                url:'http://localhost:3000/posts/2',//url大写会报错
            }).then(response=>{
                console.log(response)
            })
        }

        // 发送post请求
        var btn = document.getElementsByTagName("button")
        btn[1].onclick = function(){
            axios.request({
                method:'post',
                url:'http://localhost:3000/posts',//url大写会报错
                data: {
                    "title": "林则徐",
                    "author": "苟利国家生死以,岂因祸福避趋之"
                }
            }).then(response=>{
                console.log(response)
            })
        }

(3)、做一些默认配置

 //默认配置,如
        axios.defaults.method = 'GET',
        axios.defaults.baseURL = 'http://localhost:3000'
        axios.defaults.params = {id:1}


        var btn = document.getElementsByTagName("button")
        btn[0].onclick = function(){
            axios({
                // method:'get',
                // url:'http://localhost:3000/posts/1'
                url:'/posts'

            }).then(Response=>{
                console.log(Response)
            })
        }

(4)、创建实例对象发送请求

 //创建axios实例对象,可以在实例对象中做默认配置
        const AXIOS = axios.create({
            baseURL: 'http://localhost:3000',
            Timeout: 2000
        })
        //用实例对象发送请求,这里的AXIOS和axios对象的功能和用法几乎一样
        // AXIOS({
        //     url: '/posts/1',
        // }).then( response =>{
        //     console.log(response)
        // })
        //也可以调用方法发送请求
        AXIOS.get('/posts/1').then(response =>{
            console.log(response)
        })

(5)、拦截器

请求拦截器:在发请求之前,可以做一些逻辑处理。

响应拦截器:在受到数据之后,可以做一些逻辑处理。

//拦截器
        //请求拦截器
        axios.interceptors.request.use(function (config) {
            // Do something before request is sent
            console.log('请求拦截器 成功')
            return config;
        }, function (error) {
            // Do something with request error
            console.log('请求拦截器 失败')
            return Promise.reject(error);
        });

        //响应拦截器
        axios.interceptors.response.use(function (response) {
            // Any status code that lie within the range of 2xx cause this function to trigger
            // Do something with response data
            console.log('响应拦截器 成功')
            return response;
        }, function (error) {
            // Any status codes that falls outside the range of 2xx cause this function to trigger
            // Do something with response error
            console.log('响应拦截器 失败')
            return Promise.reject(error);
        });

(6)、取消请求

//取消请求
        let cancel = null
        var btn = document.getElementsByTagName("button")
        btn[0].onclick = function(){
            if(cancel !== null){
                cancel()
            }
            axios({
                method:'get',
                url:'http://localhost:3000/posts/1',
                //1.添加配置对象的属性
                cancelToken: new axios.CancelToken(function(c){
                    //请求正在发送时,将cancel设置为c,防止用户连续发送请求
                    cancel = c
                })
            }).then(response=>{
                console.log(response)
                //请求发送完毕将cancel设置为null,可以点击发送下一次请求
                cancel = null
            })
        }
        //取消发送
        btn[1].onclick = function(){
            cancel()
        }

源码待更新。。。

前端知识图谱+B站视频整合: 前端知识图谱+B站视频整合,以后会不断升级。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值