An article takes you to understand Axios network interaction – Vue

Time:2021-9-14

An article takes you to understand Axios network interaction - Vue

Author | jeskson

Source: dada front end Tavern

1

What is Axios?Understand and use it. What do you know about the two ways Axios sends requests, and how to solve the cross domain problems involving Axios.

For Axios network interaction, while using Axios, you should first understand what it is and how to use it. For Axios network interaction, i.e. sending requests, there are two methods mentioned above: one is to send get requests and the other is post requests.

Solve the cross domain problem of Axios.

2

If you want to use Axios, do you want to understand it and explain it. Axios is a promise based HTTP library that can be used in browsers and node environments. In applications, it sends Ajax requests to the server and obtains the corresponding HTTP request response library on the server.

Why do we use it? What are its benefits。 It can be used alone and supports promise API, which solves the problem of JavaScript “callback hell”. It can send cookies, HTTP authentication, concurrent requests, interception of requests and responses, cancel requests, etc. it can automatically convert JSON data, which is suitable for restful API scenarios.

In Vue, data is obtained from the server through Ajax. The front and back ends are separated. The back end is responsible for providing API request interface, and the front end uses Ajax to obtain server data. The server-side API interface generally uses restful API.

There are two ways to get data using Ajax:

XMLHttpRequest object
Ajax methods provided by jquery

3

What do you know about Axios? What did you do and how did you use it? Axios is widely used in Vue CLI and non Vue cli applications.There are two usage cases: one is to use Axios in Vue cli application, and the other is to use Axios in Vue file.

In the first case, in the Vue cli application, you need to create the Vue cli application, install Axios, and then configure Axios.

How to install Axios:

Use NPM or yarn, or use Vue to install Axios.

After installation, there will be an axios.js file in the plug-in directory plugins, and then the plug-in plugins will be imported in the entry file.

// main.js
import './plugins/axios'

Use Axios to get network data:

//Instance
created: function(){
 const app = this;
 Axios. Get ('interface '). Then (RES = >{
 app.users = res.data.data;
 });
}

Use Axios in the Vue file, introduce the vue.js file and axios.js file, and use Axios to send Ajax requests.

Script (import Vue. JS)
Script (import Axios. JS)

created: function(){
 //Create Vue instance and get data from Axios
 Axios. Get ('interface '). Then (function (RES){
  console.log(res.data);
 }).catch(function(error){
  console.log(error);
 });
}

Send request

Generally, send get request and send post request:

For get transmission, there are two ways to write request parameters: one is to directly attach parameters to the URL, and the other is to add get parameters using parmas attribute.

// url
axios.get('...?name=da').then(function(response){
 console.log(response.data);
 this.user = response.data.data;
 }).catch(function(error){
 console.log(error);
});

//Parmas attribute
axios.get('...', {
 params: {
  name: 'dada'
 }
})
.then(function(response){
console.log(response.data);
this.users = response.data.data;
}).catch(function(error){
console.log(error);
});

Send post request:

button(@click="addage")
addage: function(){
 const app = this;
 let params = new URLSearchParams();
 params.append('age1', 1);
 axios.post('url...', params).then(function(res){
 console.log(res.data);
 });
}

JSON format:

module.exports = function(app){
 //Configure JSON
 app.use(bodyParser.json());
 app.use(bodyParser.urlencoded({
  extended: true
 }));
};
adduser: function(){
 consot app = this;
 Axios. Post ('interface '{
 name: 'dada',
 age: 1
 }).then(function(res){
  console.log(res.data);
 });
}

if(res.data.status){
 //Data insertion succeeded
 app.user.push(res.data.data);
}

4

Cross domain problem

What is a cross domain problem is that there will be problems accessing resources in other domains, but there will be no problems accessing the same domain. How to solve this problem is called a cross domain problem.

Solutions used:

The first is to configure cross domain access through the Vue framework. The second is to modify the node program on the server side to realize the cross domain problem.

In vue.config.js in the Vue framework, configure the proxy server.

module.exports = {
devServer: {
Proxy: 'domain name'
}
};
//Proxy server processing

created:function(){
const app = this;
axios.get('/users').then(res=>{
app.users=res.data.data;
});
}

Set up agents for multiple cross domain requests, but there will still be cross domain problems in the production environment.

module.exports = {
devServer: {
//Multiple proxy requests
proxy: {
 "/api":{
  target: 'http://...',
  pathRewrite:{
   "^/api":
  }
 }
}};

created: function(){
const app = this;
axios.get('api/users').then(res=>{
app.users=res.data.data;
});
}

The server supports cross domain access

On the express server side, enable CORS for cross domain resource sharing. Before starting, install the CORS cross domain support module and introduce const CORS = require (‘cors’).

Then add middleware: app. Use (cors()).

❤️ 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

An article takes you to understand Axios network interaction - Vue