• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

测开:・《前后端交互axios》

武飞扬头像
七月的小尾巴
帮助1

前言

Axios 是一个基于 promise(异步实现) 的 HTTP 库,可以用在浏览器和 node.js 中使用,原生的js或者使用jquery来发生请求进行前后端数据交互,代码写起来过于复杂。

axios的使用

安装axios

  • 方式一
npm install axios
  • 方式二
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

axios发送get请求

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
    <script type="text/javascript">
        const request= axios.get('http://127.0.0.1:5000/api/projects')
        // 请求成功时(响应状态码为2系列)会执行then方法传入的回调函数
        request.then(function (response){
            console.log(response)
        })
        // 当请求失败,会执行catch方法传入回调函数
        res1.catch(function (error){
            console.log(error)
            console.log(error.response)
        })
        // 也可以直接使用链式调用
        axios.get('http://127.0.0.1:5000/api/projects').then(function (response){
            console.log(response)
        }).catch(function (error){
            console.log(error);
            console.log(error.response)
        })
    </script>

</body>
</html>
学新通

get请求带参数

  • 方式一:参数直接放在url中
// 把请求参数直接放在url中
const res =  axios.get('http://127.0.0.1:5000/api/pro_list?name=musen')
  • 方式二:使用params进行传递
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
    <script type="text/javascript">
        // 链式调用
        axios.get("http://127.0.0.1:5000/api/interface",{
            // 查询字符串参数传递
            params:{
                id: 1001
            }
        }).then(function (response){
            // 请求成功时执行
            console.log('res', response)
            // 获取响应状态码
            console.log(response.status)
            // 获取响应数据
            console.log(response.data)
        //    请求失败时执行
        }).catch(function (error){
            console.log(error);
            console.log(error.response)
        })
    </script>

</body>
</html>
学新通

发送post请求

  • 传递json格式的参数
        const res1 = axios.post('http://127.0.0.1:5000/api/user/login',
            {pwd: 'lemonban',user: 'python01'}
        )
  • 传递表单类型的参数
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
    <script type="text/javascript">
        // 构建一个表单参数对象
        var params = new URLSearchParams()
        params.append('user', 'python')
        params.append('pwd', 'lemonban')
        axios.post('http://127.0.0.1:5000/api/user/login', params)
        // console.log(res1)
    </script>

</body>
</html>
学新通

全局axios配置

  • 配置基本的host地址
axios.defaults.baseURL ='https://api.example.com'
  • 配置请求头信息
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN

示例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
    <script type="text/javascript">
        // 全局的请求配置信息
        axios.defaults.baseURL ='http://127.0.0.1:5000'
        axios.defaults.headers.common['Authorization'] = 'test'
        // 链式调用
        axios.get("/api/interface",{
            // 查询字符串参数传递
            params:{
                id: 1001
            },
        }).then(function (response){
            // 请求成功时执行
            console.log('res', response)
            // 获取响应状态码
            console.log(response.status)
            // 获取响应数据
            console.log(response.data)
        //    请求失败时执行
        }).catch(function (error){
            console.log(error);
            console.log(error.response)
        })
    </script>

</body>
</html>
学新通

多服务场景调用

在日常项目中,我们可能会遇到一个项目需要调用多个服务的接口,那么我们可以创建axios实例对象进行调用

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
    <script type="text/javascript">
        // 针对多个后端服务的场景
        const requestA = axios.create({
            baseURL: "http://127.0.0.1:5000",
            headers: {"test": 111}
        })
        const requestB = axios.create({
            baseURL: "http://127.0.0.1:6000"
        })

        // 链式调用
        requestA.post("/api/interface",{
            // 查询字符串参数传递
            params:{
                id: 1001
            },
        }).then(function (response){
            // 请求成功时执行
            console.log('res', response)
        }).catch(function (error){
            console.log(error);
            console.log(error.response)
        })

        // 链式调用
        requestB.post("/api/interface",{
            // 查询字符串参数传递
            params:{
                id: 1001
            },
        }).then(function (response){
            // 请求成功时执行
            console.log('res', response)
        }).catch(function (error){
            console.log(error);
            console.log(error.response)
        })
    </script>

</body>
</html>
学新通

后端鉴权的接口处理

假设我们有些接口需要鉴权,那么可以使用如下方法,获取token信息

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
    <script type="text/javascript">
         const requestB = axios.create({
            baseURL: "http://47.112.233.130:8888",
        })

        requestB.post('/users/login',{
            username: "yushaoqi",
            password: '12345',
            }
        )
        .then(function (response){
            console.log(response);
            // 提取token
            let token = response.data.token
            // 保存token到localStorage
            window.localStorage.setItem('token', token)
            // 保存到sessionStorage中,关闭浏览器之后,token会被清空
            // window.sessionStorage.setItem('token', token)
        })
        .catch(function (error){
            console.log(error.response)
        })
         
         requestB.post('project/', {
             // 接口2依赖token处理
             headers:{
                 Authorization: 'Bearer'   window.localStorage.getItem('token')
             }
         }).then(function (response){
             console.log(response)
         }).catch(function (error){
             console.log(error.response)
         })
    </script>
</body>
</html>
学新通

axios请求拦截器

前面我们请求鉴权接口的时候,每个接口都需要在其中写入token,如果只是单个接口还好,但是随着我们项目越来越庞大,几乎所有接口都需要用到token,那们我们可以把这个条件判断抽离出来。这里可以用到请求拦截器:

学新通
下面我们仍然结合登录接口,来实现案例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>测开平台</title>
    <script src='./vue.js'></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

    <style type="text/css">

        .login{
           	width: 600px;
            height: 400px;
            box-shadow: 0 0 15px #000000;
            margin: 150px auto;

            /*设置圆角*/
            border-radius: 5px;
            /*内容居中*/
            text-align: center;

        }

        .title{
            color: #00aaff;
            font: bold 24px/30px "microsoft sans serif";
            padding: 50px 0;
        }

        /*设置输入框的样式*/
        .login input{
            width: 70%;
            height: 35px;
            margin-bottom: 30px;
            border: solid 1px #d1d1d1;
            padding: 0;
            border-radius: 3px;
        }

        /*设置input键盘输入时,边框的样式*/
        .login input:focus{
            outline: none;
            border: solid 1px #ffaa00;
        }

        /*设置按钮样式*/
        .login input[type='submit']{
            background: #00AAFF;
            color: #fff;
        }

    </style>
</head>
<body>
    <div id="app">
        <div class="login">
            <div class="title">接 口 自 动 化 平 台</div>
            <form action="">
                <input type="text" v-model="loginForm.user" placeholder="  请输入用户名">
                <input type="password" v-model="loginForm.pwd" placeholder=" 请输入密码">
                <input type="button" @click="login" value="登录"/>
            </form>
        </div>
        <hr>
        <table border="" cellspacing="" cellpadding="">
            <tr>
                <th>ID</th>
                <th>项目名称</th>
<!--                <th>负责人</th>-->
<!--                <th>描述信息</th>-->
            </tr>

            <tr :key="item.id" v-for="item in projects ">
                <td>{{item.id}}</td>
                <td>{{item.title}}</td>

            </tr>

        </table>
    </div>

    <script type="text/javascript">
        const requestB = axios.create({
            baseURL: 'http://127.0.0.1:5000',
            }
        )
        // // 添加请求拦截器
        // requestB.interceptors.request.use(function (config){
        //     // 在发送请求之前做什么
        //     console.log(config)
        //     // 判断请求的是否是登录接口
        //     if(config.url === '/api/user/login'){
        //         return config
        //     }else{
        //         // 非登录接口,需要鉴权,获取localstroge中的token,添加到请求头中
        //         if(window.localStorage.getItem('token')){
        //             config.headers['Authorization'] = "Bearer"   window.localStorage.getItem('token')
        //             return config
        //         }else {
        //             alert("没有权限访问")
        //             return config;
        //         }
        //     }
        // }, function (error){
        //     // 对请求错误做些什么
        //     return Promise.reject(error);
        // });

        // 这里代码逻辑和上方注释代码一致,只是优化了一下,显示的会更简洁一些
        requestB.interceptors.request.use(function (config){
            if(config.url === '/api/user/login') return config

            if(!window.localStorage.getItem('token')) return config

            config.headers['Authorization'] = "Bearer"   window.localStorage.getItem('token')
            return config
        });

        var vm = new Vue({
          el: "#app",
          data: {
              loginForm:{
                  user: "",
                  pwd: ""
              },
              projects: []
          },
          methods:{
              login(){
                  requestB.post('/api/user/login', this.loginForm).then((response)=>{
                      console.log("请求成功", response.data)
                      if(response.data.msg === "账号或密码有误"){
                          alert("账号密码错误")
                      }else {
                           alert("登录成功")
                          // 获取token
                          let token = response.data.token
                          console.log(token)
                          // 把token放到localStorage中
                          window.localStorage.setItem('token', token)
                          this.getProject()
                      }
                  })
                      .catch(
                          function(error){
                              console.log(error.data)
                          }
                      )
              },

              getProject(){
                  requestB.get(
                      '/api/projects'
                  ).then((response)=>{
                      this.projects = response.data.results
                      console.log(this.projects)

                  }).catch(function (error){
                      console.log(error.message)
                  })

              },

          }
        })
    </script>

</body>
</html>

学新通

响应拦截器

我们有请求拦截器,就会有响应拦截器,最常见就是比如我们token失效,那么一些需要鉴权的接口都会返回401,此时我们会自动回到登录页面。
学新通
因为现在我们还未学习到路由相关的知识,所以暂时判断当状态码返回401时,我们弹窗提示

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>测开平台</title>
    <script src='./vue.js'></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

    <style type="text/css">

        .login{
           	width: 600px;
            height: 400px;
            box-shadow: 0 0 15px #000000;
            margin: 150px auto;

            /*设置圆角*/
            border-radius: 5px;
            /*内容居中*/
            text-align: center;

        }

        .title{
            color: #00aaff;
            font: bold 24px/30px "microsoft sans serif";
            padding: 50px 0;
        }

        /*设置输入框的样式*/
        .login input{
            width: 70%;
            height: 35px;
            margin-bottom: 30px;
            border: solid 1px #d1d1d1;
            padding: 0;
            border-radius: 3px;
        }

        /*设置input键盘输入时,边框的样式*/
        .login input:focus{
            outline: none;
            border: solid 1px #ffaa00;
        }

        /*设置按钮样式*/
        .login input[type='submit']{
            background: #00AAFF;
            color: #fff;
        }

    </style>
</head>
<body>
    <div id="app">
        <div class="login">
            <div class="title">接 口 自 动 化 平 台</div>
            <form action="">
                <input type="text" v-model="loginForm.user" placeholder="  请输入用户名">
                <input type="password" v-model="loginForm.pwd" placeholder=" 请输入密码">
                <input type="button" @click="login" value="登录"/>
            </form>
        </div>
        <hr>
        <table border="" cellspacing="" cellpadding="">
            <tr>
                <th>ID</th>
                <th>项目名称</th>
<!--                <th>负责人</th>-->
<!--                <th>描述信息</th>-->
            </tr>

            <tr :key="item.id" v-for="item in projects ">
                <td>{{item.id}}</td>
                <td>{{item.title}}</td>

            </tr>

        </table>
    </div>

    <script type="text/javascript">
        const requestB = axios.create({
            baseURL: 'http://127.0.0.1:5000',
            // 自定义当成功处理的http状态码范围
            validateStatus: function (status){
                return status >= 200 && status < 500;
            }
            }
        )
        // 添加请求拦截器
        requestB.interceptors.request.use(function (config){
            if(config.url === '/api/user/login') return config

            if(!window.localStorage.getItem('token')) return config

            config.headers['Authorization'] = "Bearer"   window.localStorage.getItem('token')
            return config
        });

        // 添加响应拦截器
        requestB.interceptors.response.use(function (response){
            // 在响应拦截其中,可以对响应的http状态码做相关的判断,然后进行相关的处理
            console.log("响应拦截器", response)
            if(response.code === '401'){
                // 在页面给出对应的提示
                alert(response.data.detail)
            }
            return response;
        },function (error){
            console.log(error)
            return Promise.reject(error)
        })

        var vm = new Vue({
          el: "#app",
          data: {
              loginForm:{
                  user: "",
                  pwd: ""
              },
              projects: []
          },
          methods:{
              login(){
                  requestB.post('/api/user/login', this.loginForm).then((response)=>{
                      console.log("请求成功", response.data)
                      alert("登录成功")
                          // 获取token
                          let token = response.data.token
                          console.log(token)
                          // 把token放到localStorage中
                          window.localStorage.setItem('token', token)
                          this.getProject()

                  }).catch(
                          function(error){
                              console.log(error.data)
                          }
                      )
              },

              getProject(){
                  requestB.get(
                      '/api/projects'
                  ).then((response)=>{
                      this.projects = response.data.results
                      console.log(this.projects)

                  }).catch(function (error){
                      console.log(error.message)
                  })

              },

          }
        })
    </script>

</body>
</html>

学新通

async await的使用

如果你不喜欢通过then和catch这个回调的方式来获取数据,也只可以通过async 和await的方式来处理异步部分。

学新通

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>测开平台</title>
    <script src='./vue.js'></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

    <style type="text/css">

        .login{
           	width: 600px;
            height: 400px;
            box-shadow: 0 0 15px #000000;
            margin: 150px auto;

            /*设置圆角*/
            border-radius: 5px;
            /*内容居中*/
            text-align: center;

        }

        .title{
            color: #00aaff;
            font: bold 24px/30px "microsoft sans serif";
            padding: 50px 0;
        }

        /*设置输入框的样式*/
        .login input{
            width: 70%;
            height: 35px;
            margin-bottom: 30px;
            border: solid 1px #d1d1d1;
            padding: 0;
            border-radius: 3px;
        }

        /*设置input键盘输入时,边框的样式*/
        .login input:focus{
            outline: none;
            border: solid 1px #ffaa00;
        }

        /*设置按钮样式*/
        .login input[type='submit']{
            background: #00AAFF;
            color: #fff;
        }

    </style>
</head>
<body>
    <div id="app">
        <div class="login">
            <div class="title">接 口 自 动 化 平 台</div>
            <form action="">
                <input type="text" v-model="loginForm.user" placeholder="  请输入用户名">
                <input type="password" v-model="loginForm.pwd" placeholder=" 请输入密码">
                <input type="button" @click="login" value="登录"/>
            </form>
        </div>
        <hr>
        <table border="" cellspacing="" cellpadding="">
            <tr>
                <th>ID</th>
                <th>项目名称</th>
<!--                <th>负责人</th>-->
<!--                <th>描述信息</th>-->
            </tr>

            <tr :key="item.id" v-for="item in projects ">
                <td>{{item.id}}</td>
                <td>{{item.title}}</td>

            </tr>

        </table>
    </div>

    <script type="text/javascript">
        const requestB = axios.create({
            baseURL: 'http://127.0.0.1:5000',
            // 自定义当成功处理的http状态码范围
            validateStatus: function (status){
                return status >= 200 && status < 500;
            }
            }
        )
        // 添加请求拦截器
        requestB.interceptors.request.use(function (config){
            if(config.url === '/api/user/login') return config

            if(!window.localStorage.getItem('token')) return config

            config.headers['Authorization'] = "Bearer"   window.localStorage.getItem('token')
            return config
        });

        // 添加响应拦截器
        requestB.interceptors.response.use(function (response){
            // 在响应拦截其中,可以对响应的http状态码做相关的判断,然后进行相关的处理
            console.log("响应拦截器", response)
            if(response.code === '401'){
                // 在页面给出对应的提示
                alert(response.data.detail)
            }
            return response;
        },function (error){
            console.log(error)
            return Promise.reject(error)
        })

        var vm = new Vue({
          el: "#app",
          data: {
              loginForm:{
                  user: "",
                  pwd: ""
              },
              projects: []
          },
          methods:{
              async login(){
                  // 请求登录接口,提取token
                  let response = await requestB.post('/api/user/login', this.loginForm)
                  window.localStorage.getItem('token', response.data.token)
                  this.getProject()
              },

              async getProject(){
                  let response = await requestB.get('/api/projects')
                  this.projects = response.data.results
              },
          }
        })
    </script>

</body>
</html>

学新通

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhggibgg
系列文章
更多 icon
同类精品
更多 icon
继续加载