[vue] learning note 8: vue resource implements get, post and JSON requests

Posted by SpaceLincoln on Sun, 02 Feb 2020 11:32:20 +0100

Vue resource plug-in open source address https://github.com/pagekit/vue-resource
ps: in addition to Vue resource, the third-party package of axios can also be used to implement data request

  1. In the previous study, how to initiate data request?

  2. Common data request types? get post jsonp

  3. Implementation principle of JSONP

  • Due to the security limitation of browser, it is not allowed to access data interface with different AJAX access protocol, domain name and port number, which is considered unsafe by browser;
  • The src attribute of the script tag can be dynamically created to point to the address of the data interface. Because there is no cross domain restriction on the script tag, this data acquisition method is called JSONP (Note: according to the implementation principle of JSONP, it is known that JSONP only supports Get requests);
  • Specific implementation process:
    • First, define a callback method in the client, and predefine the operation of data;
    • Then the name of the callback method is submitted to the data interface of the server in the form of URL parameters;
    • The server data interface organizes the data to be sent to the client, then takes the callback method name passed by the client, splices a string calling the method, and sends it to the client for parsing and execution;
    • After the client gets the string returned by the server, it parses and executes it as a Script script, so that it can get the data of JSONP;

Implement a request demo of JSONP

   const http = require('http');
   // Import and resolve the core module of URL address
   const urlModule = require('url');

   const server = http.createServer();
   // Listen to the request event of the server and process each request
   server.on('request', (req, res) => {
     const url = req.url;

     // Resolve the URL address requested by the client
     var info = urlModule.parse(url, true);

     // If the URL address of the request is / getjsonp, it means to get the data of JSONP type
     if (info.pathname === '/getjsonp') {
       // Gets the name of the callback function specified by the client
       var cbName = info.query.callback;
       // Manual splicing of data objects to be returned to the client
       var data = {
         name: 'zs',
         age: 18,
         gender: 'male',
         hobby: ['Having dinner', 'Sleep', 'motion']
       }
       // Splice a method call. When calling this method, serialize the data to be sent to the client into a string and pass it to the calling method as a parameter:
       var result = `${cbName}(${JSON.stringify(data)})`;
       // Return the call of the spliced method to the client for resolution and execution
       res.end(result);
     } else {
       res.end('404');
     }
   });

   server.listen(3000, () => {
     console.log('server running at http://127.0.0.1:3000');
   });

Configuration steps of Vue resource:

  • Directly in the page, the script file of Vue resource is introduced through the script tag;
  • Note: the order of reference is: first, Vue script file, then Vue resource script file;

Send get request:

getInfo() { // get data
  this.$http.get('http://127.0.0.1:8899/api/getlunbo').then(res => {
    console.log(res.body);
  })
}

Send post request:

postInfo() {
  var url = 'http://127.0.0.1:8899/api/post';
  // The post method takes three parameters:
  // Parameter 1: URL address to request
  // Parameter 2: data object to send
  // Parameter 3: specify the code type of post submission as application/x-www-form-urlencoded
  this.$http.post(url, { name: 'zs' }, { emulateJSON: true }).then(res => {
    console.log(res.body);
  });
}

Send JSONP request to get data:

jsonpInfo() { // Get data from the server in the form of JSONP
  var url = 'http://127.0.0.1:8899/api/jsonp';
  this.$http.jsonp(url).then(res => {
    console.log(res.body);
  });
}

Comprehensive use cases of get, post and JSON of Vue resource:

<!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>vue-resource Use cases</title>
  <script src="./lib/vue-2.4.0.js"></script>
  <!-- Be careful: vue-resource Depend on Vue,So we should pay attention to the order  -->
  <!-- this.$http.jsonp -->
  <script src="./lib/vue-resource-1.3.4.js"></script>
</head>

<body>
  <div id="app">
    <input type="button" value="get request" @click="getInfo">
    <input type="button" value="post request" @click="postInfo">
    <input type="button" value="jsonp request" @click="jsonpInfo">
  </div>

  <script>
    // Create Vue instance to get ViewModel
    var vm = new Vue({
      el: '#app',
      data: {},
      methods: {
        getInfo() { // Initiate get request
          //  After the get request is initiated, set the successful callback function through. then
          this.$http.get('http://vue.studyit.io/api/getlunbo').then(function (result) {
            // Get the successful data returned by the server through result.body
            // console.log(result.body)
          })
        },
        postInfo() { // Send post request application / x-www-form-urlencoded
          //  The Post request initiated manually has no form format by default, so some servers cannot process it
          //  With the third parameter of the post method, {emulateJSON: true} sets the submitted content type to the normal form data format
          this.$http.post('http://vue.studyit.io/api/post', {}, { emulateJSON: true }).then(result => {
            console.log(result.body)
          })
        },
        jsonpInfo() { // Initiate JSONP request
          this.$http.jsonp('http://vue.studyit.io/api/jsonp').then(result => {
            console.log(result.body)
          })
        }
      }
    });
  </script>
</body>
</html>
77 original articles published, 133 praised, 30000 visitors+
Private letter follow

Topics: Vue JSON github axios