Asynchronous request Axios in vue (personal study notes 5)

friendly reminder

First look at the article directory to get a general understanding of the structure of the knowledge points. You can directly click on the article directory to jump to the specified location of the article.

Chapter 1, traditional jQuery way to get data

1.1) Backend controller layer code


@Controller
@RequestMapping("/admin")
public class AdminController {
    
    
    @RequestMapping("/getAdmin.action")
    @ResponseBody
    public List<Admin> getAdmin(){
    
    
        System.out.println("接收到异步请求");
        List<Admin> adminList = new ArrayList<>();
        Admin admin = new Admin(1001, "大朗1");
        Admin admin1 = new Admin(1002, "西门1");
        Admin admin2 = new Admin(1003, "金莲1);
        adminList.add(admin);
        adminList.add(admin1);
        adminList.add(admin2);
        return adminList;
    }
}

1.2) Traditional jQuery to get data

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/jQuery3.7.js"></script>
    <script>
        $(function(){
      
      
            $.get("admin/getAdmin.action",function(adminList){
      
      
                //alert(adminList)
                var $tableDemo = $("#tableDemo");
                $.each(adminList,function(i,admin){
      
      
                    $tableDemo.append("<tr>\n" +
                        "<td>"+admin.adminId+"</td>\n" +
                        "<td>"+admin.adminName+"</td>\n" +
                        "</tr>")
                })
            },"json")
        })
    </script>
</head>
<body>
    <center>
        <table width="800px" border="1" cellspacing="0" id="tableDemo">
            <tr>
                <td>编号</td>
                <td>用户名</td>
              
            </tr>

        </table>
    </center>
</body>
</html>

1.3) Use vue object and jQuery to get asynchronous data

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/vue.js"></script>
    <script src="js/jQuery3.7.js"></script>

</head>
<body>
    <div id="root">
        <center>
            <table width="800px" border="1" cellspacing="0" id="tableDemo">
                <tr>
                    <td>编号</td>
                    <td>用户名</td>
                </tr>
                <tr v-for="admin in adminList">
                    <td>{
   
   {admin.adminId}}</td>
                    <td>{
   
   {admin.adminName}}</td>
                    
                </tr>

            </table>
            <button @click="getAdmin();">加载数据</button>
        </center>
    </div>
</body>
<script>
    new Vue({
      
      
        el:"#root",
        data:{
      
      
            adminList:[]
        },
        methods:{
      
      
            getAdmin(){
      
      
                console.log("发起异步请求前的this:",this)
                let that = this;//that就一直指向vue对象
                alert("发起异步请求")
                //发起异步请求
                $.get("admin/getAdmin.action",function(admins){
      
      
                    console.log("得到的结果:",admins)
                    //异步回执  浏览器要接收响应值  此时this指向window对象
                    //window不能读取vue中的adminList属性
                    console.log("异步成功时的回执this:",this)
                    that.adminList=admins;
                },"json")
            }
        }
    })
</script>
</html>

Chapter 2, Using Axios to Get Data

2.1) Introduction to axios

①The traditional Ajax request is based on the XMLHttpRequest (XHR) object. can be used directly. However, it is more troublesome to use and configure, and it is rarely used in actual development. In the MVC era, JQuery-Ajax is usually used. Compared with traditional Ajax, more Fetch requests are now used.
②From the beginning of the Vue2.0 era, axios is officially recommended as the new generation of Ajax library. The advantages of axios: sending XMLHttpRequest requests in the browser, sending http requests in node, supporting Promise API, intercepting requests and responses, converting request and response data, etc.

2.2) There are two ways to use axios

The first method: use cdn to import js files

 <script src="js/axios.min.js"></script>

insert image description here
The second type: import import after scaffolding installation

命令:npm install axios -S -D 
npm install -S axios@0.19.0 

insert image description here

① Add @0.19.0 to specify the version number; do not specify npm to install the latest version by default;
introduce the axios object import axios from axios where it needs to be used
-S and -D in the Npm command

--save 等同于-S(是前者的缩写):安装包信息将放入
到dependencies(生产阶段的依赖,是项目运行时的依赖,程序上线后仍然需要依赖)
--dev等价于-D(也是前者的缩写):安装包信息将放入到
devDependencies(开发阶段的依赖,是我们在开发过程中需要的依赖)

③Runtime environment and development environment
insert image description here

2.3) The config attribute of axios

More important configuration information:

method:请求方式   默认是get   get/post
url:请求路径  admin/getAdmin.action
baseUrl:基础请求路径  http://ip:port/工程名
params:请求时携带的URL参数  只能携带key-value方式的参数,params是用来携带请求参数的
data:请求时携带参数要包裹在对象格式即只能携带浏览器可以识别的对象
类型参数(Bolb  jsonStr  formData), data是用来携带请求数据的

timeOut:请求超时时间  毫秒值  
proxy:代理服务器
headers:请求头信息
responseType: "json", // 默认的  表示服务器响应的数据类型

2.4) Use axios to initiate an asynchronous request to obtain data

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/vue.js"></script>
    <script src="js/jQuery3.7.js"></script>
    <script src="js/axios.min.js"></script>

</head>
<body>
    <div id="root">
        <center>
            <table width="800px" border="1" cellspacing="0" id="tableDemo">
                <tr>
                    <td>编号</td>
                    <td>用户名</td>
                </tr>
                <tr v-for="admin in adminList">
                    <td>{
   
   {admin.adminId}}</td>
                    <td>{
   
   {admin.adminName}}</td>
                </tr>
            </table>
        </center>
    </div>
</body>
<script>
    new Vue({
      
      
        el:"#root",
        data:{
      
      
            adminList:[]
        },
        methods:{
      
      
        },
        //初始化阶段 发起异步请求  获取adminList的数据
        created(){
      
      
            let that = this;
            axios({
      
      
                url:"admin/getAdmin.action"
            }).then(function(result){
      
      
                console.log(result)
                console.log(result.data)
                console.log("axios异步请求回执:",this)
                that.adminList=result.data;
            })
        }
    })
</script>
</html>

Chapter 3, using axios to get data in springMVC

3.1) Initiate an axios request with parameters

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/vue.js"></script>
    <script src="js/axios.min.js"></script>
</head>
<body>
    <div id="root">
        <button @click="sendAxiosMethod1()">发起axios异步请求</button>
        <form>
            卡号:<input type="text" name="userName" v-model="userName"><br/>
            密码:<input type="password" name="userPwd" v-model="userPwd"><br/>
            <input type="button" value="提交" @click="loginUser1()">
        </form>
    </div>
</body>
    <script>
        new Vue({
      
      
            el:"#root",
            data:{
      
      
                userName:"",
                userPwd:""
            },
            methods:{
      
      
                sendAxiosMethod1(){
      
      
                    axios({
      
      
                        method:"get",
                        url:"demo1/axiosMethod1.action",
                        params:{
      
      
                            userName:"大朗",
                            userPwd:123
                        },
                        //responseType:"json"
                    }).then(function(result){
      
      
                        //alert(result)
                        console.log(result)
                        console.log("响应的配置信息:",result.config)
                        console.log("响应的服务器回执信息:",result.data)
                        console.log("响应头信息:",result.headers)
                        console.log("响应的状态码:",result.status)
                    })
                },
                loginUser(){
      
      
                    let loginParam={
      
      "loginName":this.userName,"loginPwd":this.userPwd}
                    let  jsonStr="{loginName:this.userName,loginPwd:this.userPwd}"//"abc"
                    console.log("请求参数:",loginParam)
                    console.log("这次的参数是params方式传递")
                    // console.log("这次的参数是data方式传递")
                    //登录
                    axios({
      
      
                        method:"post",
                        url:"demo1/loginUser.action",
                        /*params:{
                            loginName:this.userName,
                            loginPwd:this.userPwd
                        }*/
                        params:loginParam
                        //data:loginParam

                    }).then(function(result){
      
      
                        console.log(result.data)
                    });
                },
                loginUser1(){
      
      
                    //使用data方式传递参数
                    let loginParam={
      
      "loginName":this.userName,"loginPwd":this.userPwd}//js对象  json
                    console.log("loginParam:",loginParam)
                    //alert("loginParam的格式:"+typeof(loginParam))
                    //把loginParam转换成json串
                    let jsonStr = JSON.stringify(loginParam)//"{"loginName":this.userName,"loginPwd":"123"}"
                    console.log("json串后的结果jsonStr:",jsonStr)
                    //alert("jsonStr的格式:"+typeof(jsonStr))
                    //只能放在请求体  只能使用post请求
                    axios({
      
      
                        method:"post",
                        url:"demo1/getDataDemo1.action",
                        data:jsonStr,
                        headers:{
      
      
                            "Content-type":"application/json"
                        }
                    }).then(function(result){
      
      
                        console.log(result.data)
                    });

                }
            }

        });
    </script>
</html>

3.2) Backend controller layer

package com.powernode.controller;

import com.powernode.bean.LoginUser;
import com.powernode.util.ResultObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/demo1")
public class AxiosControllerDemo1 {
    
    
    //接收异步请求
    @RequestMapping("/axiosMethod1.action")
    @ResponseBody
    public ResultObject axiosMethod1(String userName,String userPwd,ResultObject resultObject){
    
    
        System.out.println("userName = " + userName);
        System.out.println("userPwd = " + userPwd);
        resultObject.setResultCode(10086);
        resultObject.setResultMessage("请求成功");
        return resultObject;
    }
    //登录处理
    @PostMapping("/loginUser.action")
    @ResponseBody
    public ResultObject loginUser(String loginName,String loginPwd,ResultObject resultObject){
    
    
        System.out.println("loginName = " + loginName);
        if(loginName.equals("888123")&& loginPwd.equals("123")){
    
    
            resultObject.setResultCode(0);
            resultObject.setResultMessage("登录成功");
        }else{
    
    
            resultObject.setResultCode(1);
            resultObject.setResultMessage("登录失败!!!");
        }
        return resultObject;
    }
    @RequestMapping("/getDataDemo1.action")
    @ResponseBody//把java对象转换成json串
    //@RequestBody  把请求中的json串解析成 json
    public ResultObject getDataDemo1(@RequestBody LoginUser loginUser){
    
    
        System.out.println("loginUser = " + loginUser);
        System.out.println("loginName = " + loginUser.getLoginName());

        ResultObject resultObject = new ResultObject();
        resultObject.setResultCode(10011);
        resultObject.setResultMessage("你好 jsonStr");
        return resultObject;
    }
}

Chapter 4, using axios to implement asynchronous file upload

4.1) Front-end code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/vue.js"></script>
    <script src="js/axios.min.js"></script>
</head>
<body>
    <div id="root">
        文件上传:<input type="file" @change="getFile($event)">
        <input type="button" value="上传" @click="fileUploadDemo()">
        <hr/>
         <!-- 根据文件路径展示在到浏览器-->
        <img :src="imgSrc"/>
    </div>
</body>
    <script>
        new Vue({
      
      
            el:"#root",
            data:{
      
      
                upFile:"",
                imgSrc:"",
                addUser:{
      
      
                    id:"",
                    name:"",
                    sex:""
                },
                updateUser:{
      
      }
            },
            methods:{
      
      
                getFile(event){
      
      
                //通过event获得需要上传的文件
                    console.log(event)
                    let upFile = event.target.files[0];
                    console.log(upFile)
                    //把得到的文件赋给了data中的upFile
                    this.upFile = upFile;
                },
                fileUploadDemo(){
      
      
                    //文件上传三要素?1 导包
                    //2 post请求  multipart/from-data  用于同步请求
                    //异步文件上传  是设置请求头headers:multipart/from-data
                    //3、配置文件上传解析器 服务器识别multipart
                    //js中有一个formData对象  是一个key-value的容器对象
                    let myF = new FormData();
                    let that = this;
                    myF.append("userName","大朗");
                    myF.append("upFile",this.upFile)
                    axios({
      
      
                        method:"post",
                        url:"demo2/upFileDemo1.action",
                        headers:{
      
      
                            "Content-type":"multipart/form-data"
                        },
                        //要上传的文件是 this.upFile,包裹在myF中通过data方式传给后端
                        data:myF
                    }).then(function(result){
      
      
                        console.log(result.data)
                        //获取文件路径回显到浏览器
                        that.imgSrc = "images/"+result.data.resultData.fileName

                    });
                }
            }


        });
    </script>
</html>

4.2) Backend controller layer code

package com.powernode.controller;

import com.powernode.bean.LoginUser;
import com.powernode.util.ResultObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
@RequestMapping("/demo2")
public class AxiosControllerDemo2 {
    
    
    @RequestMapping("/upFileDemo1.action")
    @ResponseBody
    public ResultObject upFileDemo1(String userName, MultipartFile upFile, HttpServletRequest request,ResultObject resultObject) throws IOException {
    
    
        System.out.println("userName = " + userName);
        System.out.println("upFile = " + upFile);
        String oldFileName = upFile.getOriginalFilename();
        String fileTypeName = oldFileName.substring(oldFileName.lastIndexOf("."));
        String uuid = UUID.randomUUID().toString();
        String fileName = uuid+fileTypeName;
        File file = new File(request.getServletContext().getRealPath("/images")+"/"+fileName);
        upFile.transferTo(file);
        resultObject.setResultCode(10000);
        resultObject.setResultMessage("上传成功");
        resultObject.setDataToMap("fileName", fileName);
        return resultObject;
    }
}

おすすめ

転載: blog.csdn.net/baomingshu/article/details/131892943