Axios的基本使用

一:是安装json-server的:https://github - typicode/json-serve l

Getting started

Install JSON Server

1,先安装。

npm install -g json-server

2,先创建Json-server文件夹下建一个db.json文件。

Create a db.json file with some data

{

  "posts": [

    { "id": 1, "title": "json-server", "author": "typicode" }

  ],

  "comments": [

    { "id": 1, "body": "some comment", "postId": 1 }

  ],

  "profile": { "name": "typicode" }

}

Start JSON Server

3,启动。

json-server --watch db.json

Now if you go to http://localhost:3000/posts/1, you'll get

{ "id": 1, "title": "json-server", "author": "typicode" }

二,axios安装:

Installing

Using npm:

$ npm install axios

Using bower:

$ bower install axios

Using yarn:

$ yarn add axios

Using pnpm:

$ pnpm add axios

Using jsDelivr CDN:

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

Using unpkg CDN:

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

cdn的意思是内容迸发器

1,将cdn引入到html文件中

 2,切换成国内的CDN也是可以的,BootCDN - Bootstrap 中文网开源项目免费 CDN 加速服务

收搜axios.

中国版的axios (v1.0.0-alpha.1) - Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 Node.js 中。 | BootCDN - Bootstrap 中文网开源项目免费 CDN 加速服务

axios的基本使用:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="hhttps://cdn.bootcdn.net/ajax/libs/axios/1.0.0-alpha.1/esm/axios.min.js"></script>
</head>
<style>

</style>
<body>
    <div class="container">
        <h2 class= 'page-header'>基本使用</h2>
        <button class="btn btn-primary">发送GET请求</button>
        <button class="btn btn-warning">发送POST请求</button>
        <button class="btn btn-success">发送PUT请求</button>
        <button class="btn btn-danger">发送DELETE请求</button>
    </div>

    <script>
        //获取按钮
        const btns = document.querySelectorAll('button');

        //第一个
        btns[0].onclick = function(){
            //发送ajax请求
            axios({
                //请求类型
                method:"GET",
                //url g关注连接(alt+点击)
                url: "http://localhost:3000/posts/1",

            }).then(response => {
                console.log(response);
                
            });
        }







    </script>
</body>
</html>

Axios的基本使用:

发送get请求

发送post请求

发送put请求

发送delete请求

实例:增删改查。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>axios</title>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/1.0.0-alpha.1/esm/axios.min.js"></script>
</head>
<body>
    <div class="container">
        <h2 class="page-header">基本使用</h2>
        <button class="btn btn-primary">发送GET请求</button>
        <button class="btn btn-warning">发送POST请求</button>
        <button class="btn btn-success">发送PUT请求</button>
        <button class="btn btn-danger">发送DELETE请求</button>
        
    </div>
    <script>
        //获取按钮
        const btns = Document.querySelectorAll('button') ;
        //第一个
        btns[0].onclick = function(){
            //发送ajax请求
            axios({
                //请求类型
                method:'get',
                //URL
                url:"http://localhost:300/posts/2",
            }).then(response => {
                console.log(response);
            })
        }


        //添加一篇新的文章
        btns[1].onclick = function(){
            //发送ajax请求
            axios({
                //请求类型
                method:'POST',
                //URL
                url:"http://localhost:300/posts",
                data:{
                    title:'今天天气不错,还挺缝合日历的',
                    author:"张三",
                }.then (response =>{
                    console.log(response);
                })
            })
        }

        //更新数据
        btns[2].onclick = function(){
            //发送ajax请求
            axios({
                //请求类型
                method:'PUT',
                //URL
                url:"http://localhost:300/posts/3",
                data:{
                    title:'今天天气不错,还挺缝合日历的',
                    author:"李四",
                }.then (response =>{
                    console.log(response);
                })
            })
        }

        //删除数据
        btns[3].onclick = function(){
            //发送ajax请求
            axios({
                //请求类型
                method:'DELETE',
                //URL
                url:"http://localhost:300/posts",//是要删除那个直接就写id值即可。
                data:{
                    title:'今天天气不错,还挺缝合日历的',
                    author:"李四",
                }.then (response =>{
                    console.log(response);
                })
            })
        }
                
</script>

Request method aliases

For convenience, aliases have been provided for all common request methods.

axios.request(config)

axios.get(url[, config])

axios.delete(url[, config])

axios.head(url[, config])

axios.options(url[, config])

axios.post(url[, data[, config]])

axios.put(url[, data[, config]])

axios.patch(url[, data[, config]])

1,axios的基本使用:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>axios</title>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/1.0.0-alpha.1/esm/axios.min.js"></script>
</head>
<body>
    <div class="container">
        <h2 class="page-header">基本使用</h2>
        <button class="btn btn-primary">发送GET请求</button>
        <button class="btn btn-warning">发送POST请求</button>
        <button class="btn btn-success">发送PUT请求</button>
        <button class="btn btn-danger">发送DELETE请求</button>
        
    </div>
    <script>
        //获取按钮
        const btns = Document.querySelectorAll('button') ;
        //第一个
        btns[0].onclick = function(){
            //发送ajax请求
            axios({
                //请求类型
                method:'get',
                //URL
                url:"http://localhost:300/posts/2",
            }).then(response => {
                console.log(response);
            })
        }


        //添加一篇新的文章
        btns[1].onclick = function(){
            //发送ajax请求
            axios({
                //请求类型
                method:'POST',
                //URL
                url:"http://localhost:300/posts",
                data:{
                    title:'今天天气不错,还挺缝合日历的',
                    author:"张三",
                }.then (response =>{
                    console.log(response);
                })
            })
        }

        //更新数据
        btns[2].onclick = function(){
            //发送ajax请求
            axios({
                //请求类型
                method:'PUT',
                //URL
                url:"http://localhost:300/posts/3",
                data:{
                    title:'今天天气不错,还挺缝合日历的',
                    author:"李四",
                }.then (response =>{
                    console.log(response);
                })
            })
        }

        //删除数据
        btns[3].onclick = function(){
            //发送ajax请求
            axios({
                //请求类型
                method:'DELETE',
                //URL
                url:"http://localhost:300/posts",//是要删除那个直接就写id值即可。
                data:{
                    title:'今天天气不错,还挺缝合日历的',
                    author:"李四",
                }.then (response =>{
                    console.log(response);
                })
            })
        }

2.axios其他方式发送:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>axios</title>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/1.0.0-alpha.1/esm/axios.min.js"></script>
</head>
<body>
    <div class="container">
        <h2 class="page-header">基本使用</h2>
        <button class="btn btn-primary">发送GET请求</button>
        <button class="btn btn-warning">发送POST请求</button>
        <button class="btn btn-success">发送PUT请求</button>
        <button class="btn btn-danger">发送DELETE请求</button>
        
    </div>
    <script>
        //获取按钮
        const btns = document.querySelectorAll('button');
    
        //发送get的请求
        btns[0].onclick = function(){
            axios.request({
                method:'get',
                url:'http://localhost:3000/comments',
            }).then( response => {
                console.log(response);
            })
        }
           
        //发送post请求
        btns[1].onclick = function (){
            axiox.post('http://localhost:3000/comments',
            {
                'body':"广州天气真热",
                'postId':2
            }).then(response => {
                console.log(response);
            })
       
        }

       
        
        
</script>
    
</body>
</html>

3.axios请求响应结果:

主要了解响应当中发生了哪些结果:

在控制台中:输出了response结果:

(1)config:配置对象,包括很多内容请求体,请求类型都有

(2)data:是响应体的结果,也就是服务器返回结果。是个对象,对象结果进行了json解析,方便对结果进行一个处理,所以就转成了一个对象。

(3)headers:是响应的头信息。

(4)request:是原生的ajax的请求对象,所保存的就是当前request在发送请求时创建的ajax的请求对象,也就是htmlhttprequest的实例对象。

(5)status:响应状态码

(6)statvsText:响应的状态字符串

4,axios配置对象说明 Request Config:

(1)url:指名这个请求我是要给谁去请求,设置URL这个参数

(2)method:设置请求的类型是get、put、post、delete、做设置

(3)baseURL: 'https://some-domain.com/api/',这就是一个基础结构http.....这里的baseURL会自动跟 URL合并成最终的那个URL结果。在项目当中我们可以将baseURL设置好,在发送请求的那个时候去写后面的路径,而不需要去写域名和协议。

(4)transformRequest:它可以对请求的数据做一个处理,处理完后将结果发送给服务器。

(5)transformResponse:可以对响应的结果做一些改变,改名后我们在用自定义的回调去处理这个结果。

(6)headers: {'X-Requested-With': 'XMLHttpRequest'}, 这个是对请求头信息做一个配置。进行身份校验的时候,要加入一个特殊的标识,就可以有到他

(7)params:是要设定URL参数的,例如要向服务端发个请求,在发送请求时,在url后面要发送请求参数,a=100。可以在对象当中去设置这个配置。

5,axios默认设置:

// 距离默认配置
        axios.defaults.method = "get"  //设置默认的请求类型为get
        axios.defaulrs.url = "http://localhost:3000";//设置基础url
        axios.defaulrs.params = {id:100};
        axios.defaulrs.timeout = 3000;

//原先代码:
        btns[0].onclick = function (){
            axiox.post('/post)',
            {
                'url':"广州天气真热",
           
            }).then(response => {
                console.log(response);
            })
        }

6,axios创建实例对象发送请求:

<body>
    <div class="container">
        <h2 class="page-header">基本使用</h2>
        <button class="btn btn-primary">发送GET请求</button>
        <button class="btn btn-warning">发送POST请求</button>
        
    </div>
    <script>
        //获取按钮
        const btns = document.querySelectorAll("button");
        //创建实例对象 、getjoke
        const duanzi = axios.cteate({
            baseURL:'http://api.apionpen.top',
            timeout:2000,
        });
        // 
        这里的duangzi与axios对象的功能几乎都是一样的
        duanzi({
            url:'getjoke',
        }).then(response => {
            console.log(response);
        })

        //以上还可以简写成:
        duanzi.get('/getJoke').then(response =>{
            console.log(response.data);
        })

假设那有多个服务器,那要设置默认时,需要找对应的域名进行设置。

 

 7,axios拦截器  很重要

拦截器interceptors就是一些函数,分两大类:一种是请求拦截器,另外一种是响应拦截器。

请求拦截器:就是在发送请求之前,借助一些回调,来对请求的参数和内容做一些处理和检测,如果没有问题直接发送请求,有问题可以停止取消。

响应拦截器:当服务器返回结果时,响应拦截器它可以在我们处理结果之前,对这些结果做一个预处理,失败了做提醒做记录;还可以对数据接口做一些处理,在交由自己的回调来处理。

<script>
    //Promise
        //添加设置一个请求拦截器
    axios.interceptors.request.use(function (config) {
       console.log('请求拦截器 成功');
        return config;
    }, function (error) {
        console.log('请求拦截器 失败');
        return Promise.reject(error);
    });

    //设置响应拦截器
    axios.interceptors.response.use(function (response) {
        console.log('响应拦截器 成功');
        return response;
    }, function (error) {
        console.log('响应拦截器 成功');
        return Promise.reject(error);
    });
    //发送请求
    axios({
        method:'get',
        url:'http://localhost:3000/posts'
    }).then(response =>{
        console.log('自定义回调成功的结果');
    })
</script>
    

8,axios取消请求:

了解一下request config  对象

url +baseURl成为最终的URL结果

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值