Axios network interactive application – Vue

Time:2021-9-3

Axios network interactive application - Vue

Author | jeskson

Source: dada front end Tavern

<template>
 <div id="app">
 <input type="text" placeholder="name" v-model="user.name">
 <input type="text" placeholder="age" v-model="user.age">
 <button type="button" class="btn" @click="btn.clickcallback">
 {{btn.text}}
 </button>
 <table class="table">
  <thead>
   <tr>
    <th>id</th>
    <th>name</th>
    < th > operation < / th >
   </tr>
  </thead>
  <tbody>
   <tr v-for="item,index) in users" :kkey="index">
    <td scope="row">{{item.id}}</td>
    <td>{{item.name}}</td>
 
    <td>
     <a class="btn" href="#" role="button"
     @Click. Prevent = "edituser (index)" > Edit</a>
     < a class = "BTN" href = "#" role = "button" @ click. Prvent = "deleteuser (index)" > delete</a>
     </td>
    </tr>
    </tbody>
    </table>
    </div>
    </template>
    <script>
    import "bootstrap/dist/css/boostrap.css";
    export default {
     name: 'app',
     data(){
     return {
      users: [],
      //Add data
      user: {},
      editindex: -1,
      btn: {
       Text: 'Add User',
       clickcallback: this.adduser
      }
     };
    },
    methods: {
     adduser(){
     const app = this;
     axios.post('/api/users',this.user).then(res=>{
     app.users.push(res.data.data);
     app.user ={};
    });
   },
   edituser(index){
   this.editindex = index;
   this.user = this.users(index);
   this.btn={
   Text: 'edit user',
   clickcallback: this.doedituser
   };
  },
  doedituser(){
  axios.put('/api/users/'+this.users[this.editindex].id,this.user).then(res => {
  app.editindex=-1;
  app.user ={};
  app.btn={
  Text: "add user",
  clickcallback: app.adduser
 };
});
},
//Delete user
deleteuser(index) {
const app = this;
axios.delete('/api/users/'+this.users[index].id).then(function(res){
if(res.data.status){
app.users.splice(index,1);
}
};
}
},
//Axios network requests data
created: function(){
const app = this;
axios.get('/api/users').then(res=>{
app.users=res.data.data;
})
}
}
</script>

Axios is a promise based HTTP library that can be used in browsers and node.js

The following services can be provided:

1. Create xmlhttprequests from the browser
2. Create HTTP request from node.js
3. Support promise API
4. Intercept requests and responses
5. Convert request data and response data
6. Cancel request
7. Automatically convert JSON data
8. Client support defense xsrf

What is the command for Vue to install the Axios plug-in?

Installation of Axios:

Installation command; npm install axios

Get: generally used to obtain data

Post: mainly submit form data and upload files

Put updates all data

The request is similar to post, except that the request method is different

Patch updates only the changed data

The request is similar to post, except that the request method is different

Delete delete request

Parameters can be placed on the URL or in the request body like post

Axios is the encapsulation of Ajax requests

Native Ajax request implementation

//Step 1: create an asynchronous object
var ajax = new XMLHttpRequest();
//Step 2: set the URL parameters of the request. The first parameter is the type of the request and the second parameter is the URL of the request. You can dynamically pass the parameter starname to the server with parameters
ajax.open('get', 'http://。。。');
//Step 3: send request
ajax.send();
//Step 4: the registration event onreadystatechange will be called when the state changes
ajax.onreadystatechange = function () {
    if (ajax.readyState == 4 && ajax.status == 200) {
        //Step 5: if you can enter this judgment, the data has come back perfectly, and the requested page exists
        console.log(ajax.responseText);// Enter the corresponding content
    }
}
//Create asynchronous object  
var xhr = new XMLHttpRequest();
//Set the type and URL of the request
//Open XHR
xhr.open('post', 'http://。。。');
//You must add a request header to a post request, otherwise an error will be reported
//Set the request header. The request header must be set after XHR is opened and before send
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//Send request
xhr.send();
xhr.onreadystatechange = function () {
    //This step is to determine whether the server responds correctly
    if (xhr.readyState == 4 && xhr.status == 200) {
        console.log(xhr.responseText);
    }
};
//Set baseurl for Axios
axios.defaults.baseURL = ' https:、api';

let url = /film/getList';
axios.get(url).then(res => {
    console.log(res);
})
//Set request header
axios.defaults.headers['sessionToken'] = 'asd234';

Homology strategy:

The generation of cross domain is derived from the "homology strategy" commonly used in modern browsers. The so-called homology strategy refers to that only in the address:
  1. Protocol name
  2. domain name
  3. port name

Access to the same cookie, localstorage, sending Ajax requests, etc. is only allowed under the same circumstances. If it is accessed from different sources, it is called cross domain.

How to solve the Axios cross domain problem?

terms of settlement:

Server (background) settings allow cross domain

Browser settings cross domain

Allow cross domain through proxy

header('Access-Control-Allow-Origin:*');
//Allow access from all sources 
header('Access-Control-Allow-Method:POST,GET');
//Ways to allow access

Interceptors are divided into:

Request interceptor and response interceptor

Create an Axios instance through Axios. Create

//Create Axios object

let $axios = axios.create({
    baseURL: 'http://。。。'
})

Request interceptor

//Intercept request before sending
$axios.interceptors.request.use(res=> {
    //Add request header
    res.headers.sessionToken = 'as423424..';
    return res;
})

Response interceptor

//Intercept response response after data return
$axios.interceptors.response.use(function (res) {
    if (res.data.code === '200') {
        return res.data;
    } else {
        alert(res.data.msg);
    }
}, function (error) {
    Alert ('network exception ');
})

Remember to share!

❤️ Don’t forget to leave your learning footprints [like + collect + comment]

Author Info:

[author]: jeskson
Official account: dada’s front bar.
[welfare]: the official account answers the “information”, sends the gift package of self study materials (enter group to share, want to say anything ha, see if I have).
[reprint description]: please explain the source of reprint. Thank you for your cooperation~

Large front-end development, positioning front-end development technology stack blog, PHP background knowledge points, web full stack technology field, data structure and algorithm, network principle and so on. Thank you for your support, thanks for your love!!!


If the content of this number is not in place (for example, involving copyright or other problems), please contact us in time for rectification and will deal with it at the first time.


Please praise! Because your approval / encouragement is the biggest driving force for my writing!

Welcome to dada’s CSDN!

This is a blog with quality and attitude

Axios network interactive application - Vue