Previous Data Request

Keywords: axios PHP Vue JSON

Data Request

Data request: Axios fetch

  • How to request data

  • Native

    • ajax fetch
  • encapsulation

    • jq
    • Vue 1.x vue-resource abandonment test
    • axios is now the best encapsulated request library [framework project]
      • axios and vue-resource similarity 98%

1.axios

  • Reference: cdn of axios can be introduced into bootcdn

  • Static request: getStatic

    getStatic () {
            // Getting static data
            // console.log( axios(options) )
            // console.log( axios({}) ) // Promise
    
            // axios.get()
            // axios.post()
    
            axios({
              url: './mock/data/movie.json',
              method: 'GET'
            }).then( res => console.log( res ))
              .catch( error => console.log( error ))
    
          }
    
  • Get request:get

    get () {
            axios
              .get('http://localhost/get.php',{
                params: {
                  a: 1,
                  b: 2
                }
              })
              .then( res => console.log( res ))
              .catch( error => console.log( error ))
    //Or
    axios({
                url: 'http://localhost/get.php',
                method: 'GET',
                params: {
                  a: 1,
                  b: 2
                }
              }).then( res => console.log( res ))
                .catch( error => console.log( error ))
    
          }
    
  • post request:

    // The following code sets the request header for the post request uniformly
    axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
    post () {
            // axios.post('http://localhost/post.php',{
            //   a: 1,
            //   b: 2
            // }).then( res => console.log( res ))
            //   .catch( error => console.log( error ))
    
    
            const params = new URLSearchParams()
    
            // params.append(key,value)
            params.append('a',1)
            params.append('b',2)
    
            axios({
              method: 'post',
              url: 'http://localhost/post.php',
              data: params
            }).then( res => console.log( res ) )
              .catch( error => console.log( error ))
    
          }
    
  • vue-resource

    Replace the axios() above with this.$http

    But vue-resource has a method called jsonp that axios does not have.

  • Case list

    <!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> axios Data Request </title>
      <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
      <script src="https://cdn.bootcss.com/axios/0.19.0/axios.js"></script>
    </head>
    <body>
      <div id="app">
        <div class="container">
          <div class="row">
            
            <h3> Static Request [Analog Data] </h3>
              <button type="button" class="btn btn-primary" @click = "getStatic" > getJson </button>
              <hr>
            <h3> Dynamic Request [Real Interface] </h3>
              <button type="button" class="btn btn-primary" @click = "get"> get </button>
              <button type="button" class="btn btn-primary" @click = "post"> post </button>
          </div>
        </div>
      </div>
    </body>
    <script src="../../lib/vue.js"></script>
    <script>
      /* 
        After introducing axios cdn, we will get a global variable of axios
      */
      // The following code sets the request header for the post request uniformly
      axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
      new Vue({
        el: '#app',
        methods: {
          getStatic () {
            // Getting static data
            // console.log( axios(options) )
            // console.log( axios({}) ) // Promise
    
            // axios.get()
            // axios.post()
    
            axios({
              url: './mock/data/movie.json',
              method: 'GET'
            }).then( res => console.log( res ))
              .catch( error => console.log( error ))
    
          },
          get () {
            axios
              .get('http://localhost/get.php',{
                params: {
                  a: 1,
                  b: 2
                }
              })
              .then( res => console.log( res ))
              .catch( error => console.log( error ))
    
    
              axios({
                url: 'http://localhost/get.php',
                method: 'GET',
                params: {
                  a: 1,
                  b: 2
                }
              }).then( res => console.log( res ))
                .catch( error => console.log( error ))
    
          },
          post () {
            // axios.post('http://localhost/post.php',{
            //   a: 1,
            //   b: 2
            // }).then( res => console.log( res ))
            //   .catch( error => console.log( error ))
    
    
            const params = new URLSearchParams()
    
            // params.append(key,value)
            params.append('a',1)
            params.append('b',2)
    
            axios({
              method: 'post',
              url: 'http://localhost/post.php',
              data: params
            }).then( res => console.log( res ) )
              .catch( error => console.log( error ))
    
          }
        }
      })
    </script>
    </html>
    

2.fetch

  • fetch is provided by native javascript and can be used directly as a global variable

  • fetch is also Promise

  • The results returned by fetch are not encapsulated and are directly exposed.

  • What are the formatting methods of fetch data/

  • json()

  • text()

  • blob() formatting binary [video, image and audio]

  • post requests have pits

  • Case list

    <!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> fetch </title>
      <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/4.0.0/css/bootstrap.min.css"
        integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    
    </head>
    
    <body>
      <div id="app">
        <div class="container">
          <div class="row">
    
            <h3> Static Request [Analog Data] </h3>
            <button type="button" class="btn btn-primary" @click="getStatic"> getJson </button>
            <h3> Dynamic Request [Real Interface] </h3>
            <button type="button" class="btn btn-primary" @click="get"> get </button>
            <button type="button" class="btn btn-primary" @click="post"> post </button>
          </div>
        </div>
      </div>
    </body>
    <script src="../vue.js"></script>
    <script>
    
      new Vue({
        el: '#app',
        methods: {
          getStatic() {
            //Using fetch to request mock data
    
            fetch('./mock/data/data.json')
              .then(res => res.json())  // Formatting Data 
              .then(data => console.log(data))  // Get data formatted
              .catch(error => console.log(error)) // Error capture
    
          },
          get() {
            //Using fetch to request dynamic data get
    
            fetch('http://localhost/get.php?a=1&b=2')
              .then(res => res.text())  // Formatting Data 
              .then(data => console.log(data))  // Get data formatted
              .catch(error => console.log(error)) // Error capture
    
          },
          post() {
            // Using post to request dynamic data
    
            fetch('http://localhost/post.php', {
              method: 'POST', // or 'PUT'
              body: new URLSearchParams([['a', 1], ['b', 2]]).toString(),
              headers: new Headers({
                'Content-Type': 'application/x-www-form-urlencoded'
              })
            }).then(res => res.text())
              .catch(error => console.error('Error:', error))
              .then(response => console.log('Success:', response));
    
          }
        }
      })
    </script>
    
    </html>
    

3. Summary

  • axios vs fetch post requests have some problems

  • Processing methods

    1. Set the request header first
    2. Passing parameters through new URLSearchParams

Posted by wmolina on Tue, 30 Jul 2019 18:45:02 -0700