axios Network Interaction Application-Vue

Keywords: Front-end axios network JSON Vue

Author| Jeskson

Source|Dada Front End Bistro

<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 request for 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 a browser 2. Create http requests from node.js 3. Support PromiseAPI 4. Intercept requests and responses 5. Transform request and response data 6. Cancel Request 7. Automatically convert JSON data 8. Client Support Defense XSRF

What is the command for Vue to install axios plug-ins?

** Installation of axios: **

Installation command; npm install axios

Get:Usually used to get 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 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 body of the request as post s

axios is an encapsulation of ajax requests

Native ajax request implementation

//Step 1: Create an asynchronous object
var ajax = new XMLHttpRequest();
//Step 2: Set the url parameter of the request. The first parameter is the type of request and the second parameter is the url of the request. It can transfer the parameter starName to the server dynamically with parameters.
ajax.open('get', 'http://. . . ');
//Step 3: Send the request
ajax.send();
//Step 4: The registration event onreadystatechange will be invoked when the state changes
ajax.onreadystatechange = function () {
    if (ajax.readyState == 4 && ajax.status == 200) {
        //Step 5 If you can enter this judgment, the data is back perfectly and the requested page exists
        console.log(ajax.responseText);//Enter the appropriate content
    }
}
//Create Asynchronous Object  
var xhr = new XMLHttpRequest();
//Set the type and url of the request
//Open xhr
xhr.open('post', 'http://. . . ');
//A post request must have a request header added or an error will occur
//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 is to determine if the server is responding 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 policy:

  Cross-domain originates from the'homology policy'commonly used by modern browsers, which refers to address-only: 
  1. Protocol Name
  2. domain name
  3. port name

In the same case, access to the same cookie, local store, send Ajax requests, and so on is allowed.If accessed from different sources, it is called cross-domain.

How can I solve the axios cross-domain problem?

Solution:

Server (Background) settings allow cross-domain

Browser Settings Cross Domain

Allow cross-domain through proxy

header('Access-Control-Allow-Origin:*');
//Allow access to all sources 
header('Access-Control-Allow-Method:POST,GET');
//How access is allowed 

Interceptors are divided into:

request interceptor and response interceptor

Create an Axios instance from axios.create

// Create axios object

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

request Interceptor

// Intercept request-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 it!

Don't forget to leave a footprint of your study [compliment + collection + comment]

Author Info:

[Author]: Jeskson Original Public Number: Dada Front End Bistro. Welfare: Public Number replies to the big gift package for self-study materials (share in groups, just say anything you want, see if I have one)! [Reprint instructions]: Please explain the source of reprinting, thank you for your cooperation!~

Big Front End Development, Locate Front End Development Technology Stack Blog, PHP Background Knowledge Point, web Full Stack Technology Field, Data Structure and Algorithms, Network Principles and other understandable presentations to small partners.Thank you for your support and love!!!

If there are inadequacies in this number (e.g. copyright or other issues), please contact us in time to make corrections, which will be dealt with at the first time.

Please compliment!Because your approval/encouragement is my greatest motivation to write!

Welcome to your attention Dada CSDN!

This is a quality, attitudinal blog

Posted by kumarsatishn on Mon, 23 Dec 2019 18:53:38 -0800