Vue project installs Axios to implement HTTP request

Contents of articles

First, install Axios. Second, use axios1. Introduce axios2. Get method. Third, post method

summary


preface

we all know that the front end needs to request some data and services asynchronously from the back end, which is the so-called Ajax technology. and Vue.js It has no Ajax capability, so it needs to use Axios to complete the Ajax request.


1、 Install Axios

Axios is a promise based HTTP library, which can be used in browsers and websites node.js Medium

Using NPM:

$ npm install axios

Using yarn:

$ yarn add axios

note: install in the root directory of Vue project, and select the configuration file of the project package.json With the corresponding version number, the installation is successful

2、 Using Axios

1. Introducing Axios

stay main.js When the file is injected into Axios:

import axios from 'axios'
Vue.prototype.$axios = axios  //The $axios before the equal sign can be replaced with another name, but use it consistently 

2. Get method

a relatively complete format: </ font>

this.$axios({ //The $axios here is the one named in main.js
            method: "get",
            url: "http://wthrcdn.etouch.cn/weather_mini",//an API for querying city weather
            headers:{
              'Content-type': "application/json;charset=utf-8"
            },
            params : { 
              city : "GuangZhou"
            },
            dataType:'json',
          })
          .then((res)=>{
            console.log(res.data);
            console.log("success")
          })
          .catch(function (error) {
            console.log(error);
            alert("Failed to connect server");
            console.log("fail")
          });

3. Post method

a relatively complete format: </ font>

this.$axios({
            method:"post",
            url:"http://test/...",
            headers:{
              'Content-type': "application/json;charset=utf-8"
            },
            data : { 
              a : '',
              b : ''
            },
            dataType:'json',
          })
          .then((res)=>{
            console.log(res.data);
            console.log("success")
          })
          .catch(function (error) {
            console.log(error);
            alert("Failed to connect server");
            console.log("fail")
          });

summary

for Axios, it is not too difficult to use without studying its principle. And through the above get and post methods, we can also find that its syntax is very similar to jQuery’s Ajax, and we can easily use it.

Read More: