Vue asynchronous request

vue initially uses vue resource to implement asynchronous request (ajax), and vue 2.0 began to recommend using axios instead of vue resource.

 

Preparation

1. Download axios using npm

npm install axios

 

2. Introducing axios.js

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

Change to min.js when online

 

 

 

 

The front-end vue uses axios to initiate asynchronous requests

You can write as follows:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title></title>
        <!-- Introduce vue.js -->
        <script src="js/vue.js"></script>
        <!-- Introduce axios.js -->
        <script src="js/axios.js"></script>
    </head>
    <body>
        
    <div id="app"></div>

    <script>
        
        new Vue({
            el:'#app',
            template:`
                <div>
                    <button @click="login">Send out</button>
                </div>
            `,
            data(){
                return{
                    
                }
            },
            methods:{

                  login:function() {
                      axios.post('/login', {  //get|post Optional, use object{ }Transfer data, if not, default{ }. get Mode parameters can also be spliced in url in
                          username: 'chy',   //It's usually getting form data, $('#xxx').val
                          password: 'abcd'
                      }).then(function (response) {  //Process the data returned in the background.
                          console.log(response);  //response Is the entire response returned in the background
                          console.log(response.data);  //.data Is the data returned by the background
                      }).catch(function (error) {  //Handling when an error occurs
                          console.log(error);
                      });
                  }

            }

        })
    
    </script>        
        
    </body>
</html>
 

If you don't need to return data in the background, don't then. catch is not required either.

 

 

You can also write as follows:

    methods:{

          login:function() {
              axios({
                  method:'post',  //Request mode
                  url:'/login',  //Background interface
                  data:{  //Data transferred to the background
                      username: 'chy',
                      password: 'abcde'
                  }
              }).then(function (response) {
                  console.log(response);  //response Is the entire response returned in the background
                  console.log(response.data);  //.data Is the data returned by the background
              }).catch(function (error) {  //Handling when an error occurs
                  console.log(error);
              });
          }

    }

This is not cross domain. If it is cross domain, the url should write host|ip:port/xxx, and write all.

When an asynchronous request is initiated, the resultType can be used to specify the data type (text, json, stream) that is expected to be returned. However, it is not necessary to identify the returned data type automatically.

 

 

 

 

Processing ajax requests in the background

@Controller
// @ResponseBody  //@ResponseBody It can be written on a class or a method. When it is written on a class, it takes effect on all methods in the class
// @RestController  //@RestController Amount to@Controller+@ResponseBody
public class UserController {

    @RequestMapping("/login")
    @ResponseBody  //If you want to return data to the front end, you need to use the@ResponseBody Modify the method to json Form, otherwise it will be treated as the view name
    public String login(@RequestBody Map<String,String> map) {  //If you want to receive ajax One and only one parameter must be used for the parameter passed in Map To receive parameters, and use the@RequestBody Tagging
        String username = map.get("username");  //Obtain ajax Parameters passed
        String password = map.get("password");
        System.out.println(username);
        System.out.println(password);

        return "ok";  //Data returned to the front end. If no data is returned, the return value type is set to void that will do

    }

}

 

 

The above demo does not involve cross domain requests. If the requests are to cross domains, the front-end and back-end need to make some other settings.

 

 

 

Background return data sample

@RestController  //Amount to@Controller+@ResponseBody
public class UserController {

    //Return text|Character string
    @RequestMapping("/login1")
    public String login1() {
        return "hello";
    }

    //Return object
    @RequestMapping("/login2")
    public User login2() {
        User user = new User("chy", "abcd");
        return user;
    }

    //Return Map. Map and pojo Class is the same thing. It's all about acting json Object return
    @RequestMapping("/login3")
    public Map<String,Object> login3() {
        HashMap<String, Object> map = new HashMap<>();
        map.put("username", "chy");
        map.put("age", 20);
        return map;
    }

    //Return List,with json Return as an array
    @RequestMapping("/login4")
    public List login4() {
        User user1 = new User("chy1", "abcd");
        User user2 = new User("chy2", "abcd");
        User user3 = new User("chy3", "abcd");
        ArrayList<User> userList = new ArrayList<>();
        userList.add(user1);
        userList.add(user2);
        userList.add(user3);
        return userList;
    }

}

 

 

 

 

Front end take out data example

.then(function (response) {
      console.log(response.data);  //Retrieve the returned data, string|object|Map|List
      // console.log(response.data.username);  //Take out the value of a field of the object | Map
      // console.log(response.data[0]);  //Take an element out of the List
      // console.log(response.data[0].username);  //Take the value of a field of an element in the List
  })

 

 

 

Explain

When debugging, the Chrome console reports an error: Net:: err ﹣ socket ﹣ not ﹣ connected. Refresh it several times or clear the cache.

Keywords: Javascript axios Vue JSON npm

Added by RiBlanced on Fri, 10 Apr 2020 17:44:55 +0300