VUE's axios summary

Table of contents

what is axios

Features

Request type

Define axios prefix

Axios writing format

Attribute information

The difference between params and data

params

data 

Use Cases

before use

axios abbreviation

Notice:

abbreviation form practice

Usage for different request types 

post form and put form

get form and delete form

Parameter splicing form of get form and delete

restful form 

Notice:

Usage

Global reference axios

Encapsulation of axios network requests

Packaging solution

Cross-domain solution for network requests

js adopts the same origin policy

non-homogeneous restriction

Solution to cross-domain issues

Front desk cross-domain solution case

The front-end accesses the back-end service through a proxy

Backend services

what is axios

Axios (ajax input output system) is an open source asynchronous communication framework that can be used on the browser side and node.js side. Its main function is to implement ajax asynchronous communication.

Features

  1. Create xmlHttpRequests from the browser
  2. Create http request from node.js
  3. Intercept requests and responses
  4. Convert request data and response data
  5. Cancel request
  6. Automatically convert json data
  7. The client supports defense against xsrf (cross-site request forgery attack)

Note: Ajax is encapsulated and enhanced in Vue, which is better than native Ajax in asynchronous and concurrent processing.

Request type

  • post: new operation
  • put: modification operation
  • get: query operation
  • delete: delete operation 

Define axios prefix

Writing method: axios.defaults.baseURL="prefix name"

Result: After writing the prefix, the subsequent axios request path can be abbreviated (remove the prefix)

Axios writing format

axios({
    url:"地址信息",
    method:"请求方法",
    params:{name:"lili"},
    data:{name:"lili"}
}).then(res=>{
    <!--结果被封装到promise的data中-->
    console.log(res.data)
})

Attribute information

  • url: requested path
  • method: request method
  • params: request parameters
  • data: request parameters

The difference between params and data

params

  • Send request parameters in the format of name=value&name=value in the form of params, and the parameters transferred are unformatted objects.
  • Regardless of whether the request method used is get or post, the request parameters will be spliced ​​to the request address.
  • Data in this way can directly obtain parameters

data 

  • data is to send request parameters in the form of json string
  • The request parameters will be saved in the request body of the request message.
  • The parameters obtained in this way are json and you need to convert them into java objects.
  • This method is only applicable to put, post, and patch methods (get method has no request body)

Use Cases

before use

Install axios: npm install --save axios

Install querystring: npm install --save querystring

Introduced in the component:

import axios from "axios"

import querystring from "querystring"

<template>
<div id="a">
    {
   
   {msg}}
</div>
</template>
<script>
import axios from "axios"
import querystring from "querystring"
export default{
    name:"mycomponent",
    data() {
        return {
            msg:""
        }
    },
    mounted() {
        // get请求方式
        axios({
            method:"get",
            url:"https://limestart.cn/"
        }).then(res =>{
            console.log(res.data);
            this.msg=res.data
        })
    // post请求参数
    axios({
        method:"post",
        url:"http://iwenwiki.com/api/blueberrypai/login.php",
        data:querystring.stringify({
            user_id:"[email protected]",
            password:"iwen123",
            verification_code:"crfvw"
        })
    }).then(res=>{
        console.log(res.data);
    })
    },
}
</script>

Note: The data in data must be passed in json format

axios abbreviation

axios.请求方法("url地址信息",参数信息)
.then(function(promise){console.log(promise.data)}) 

Notice:

  • axios. The request method ("url address information", parameter information) is a promise object, and the request result is encapsulated into the data attribute.
  • Use the return value of the "axios.request method ("url address information", parameter information)" function as the parameter of the upcoming callback function, promise 

abbreviation form practice

<template>
<div id="a">
    {
   
   {msg}}
</div>
</template>
<script>
import axios from "axios"
import querystring from "querystring"
export default{
    name:"mycomponent",
    data() {
        return {
            msg:""
        }
    },
    mounted() {
        // get请求方式
        axios.get("https://limestart.cn/")
        .then(res=>{
            console.log(res.data);
        })
        // post请求参数
        axios.post("http://iwenwiki.com/api/blueberrypai/login.php",querystring.stringify({
            user_id:"[email protected]",
            password:"iwen123",
            verification_code:"crfvw"
        })).then(res=>{
        console.log(res.data);
        })
    },
}
</script>

Usage for different request types 

post form and put form

axios.请求方法("url地址",对象名称) 
.then(function(promise){console.log(promise.data)}) 

get form and delete form

axios.请求方法("url地址",{params:对象名称}) 
.then(function(promise){console.log(promise.data)}) 

Note: For {params: object name} parameter browser will parse the object inside and then automatically splice the parameters.

Parameter splicing form of get form and delete

Parameter splicing url writing method: http://localhost:8080/del?age=9&name=lili&hobby=basketball&hobby=football

Understanding parameter splicing: What are the attributes behind the path? Separate, connect multiple attributes with &

axios.请求方法("url地址带拼接参数") 
.then(function(promise){console.log(promise.data)})  

restful form 

Restful form of writing: http://localhost:8080/del/9/lili

Restful form understanding: use / splicing between paths and parameter values

Notice:

  • Restful writing parameter value is edited in the url
  • Use / to separate parameters from each other
  • Restful splits data locations in a strict order (just think about it)
  • In the restful structure, verbs cannot appear in the request path for hiding purposes.
  • The restful format supports get/post/put/delete and other request methods.  
  • If the restful request is post/put, the following object name needs to be written.

Usage

axios.请求方法("url地址信息restful形式",[对象名称])
.then(function(promise){console.log(promise.data)}) 

Global reference axios

import { createApp } from 'vue'
import App from './App.vue'
import './registerServiceWorker'
//引入axios
import axios from "axios"
const app=createApp(App)
//将axios挂载到全局
app.config.globalProperties.$axios=axios
// 使用时直接this.$axios()来调用axios
app.mount('#app')

Encapsulation of axios network requests

Preface: In the daily application process, there will be many network requests in a project. At this time, the generally adopted solution is to encapsulate the network requests.

Packaging solution

Install axios: npm install --save axios

Install querystring: npm install --save querystring

Introduced in the component:

import axios from axios

import querystring from "querystring"

import axios from "axios"
import querystring from "querystring"

const errorHandle=(status,info)=>{
    switch(status){
        case 400:
            console.log("语义有误");
            break
        case 401:
            console.log("服务器认证失败");
            break
        case 403:
            console.log("服务器拒绝访问");
            break
        case 404:
            console.log("地址错误");
            break
        case 500:
            console.log("服务器遇到意外");
            break
        case 502:
            console.log("服务器无响应");
            break
        default:
            console.log(info);
            break
    }
}
/* 创建自己的网络请求对象 */
const instance=axios.create({
    /* 网络请求的公共配置 */
    timeout:5000
})
//拦截器常用
//发送数据之前
instance.interceptors.request.use(
    //拦截成功执行的函数
    //config包含网络请求的所有信息
    config=>{
        if(config.methods==="post"){
            /* 转化post请求参数格式 */
            config.data=querystring.stringify(config.data)
        }
        return config
    },
    //拦截失败执行的函数
    error=>{
        return Promise.reject(error)
    }
)
//获取数据之前
instance.interceptors.response.use(
    //成功时返回结果
    response=>{
        return response.status===200?Promise.resolve(response):Promise.reject(response)
    },
    //失败时返回结果
    error=>{
        const {response}=error
        // 错误处理才是重中之重
        errorHandle(response.status,response.info)
    }
)
export default instance

Usage: Directly introduce this exported instance as an axios instance and use it directly 

Cross-domain solution for network requests

js adopts the same origin policy

The same origin policy is a browser security policy. The browser only allows js code to request data on the data interface with the same domain name, port, and protocol as the current server. This is the same origin policy.

Understanding: When any of the protocols, domain names, and port numbers are different, cross-domain problems will occur.

non-homogeneous restriction

  • Unable to read cookies, localStorage and IndexedDB of non-original web pages
  • Unable to access the DOM of non-original web pages
  • Unable to send ajax request to non-original address 

Solution to cross-domain issues

  • Backend solution: cors
  • Front desk solution: proxy

Front desk cross-domain solution case

The front-end accesses the back-end service through a proxy

<template>
  <div id="container">
    <button @click="send">点击调用</button>
  </div>
</template>
<script>
export default {
  name:"app",
  methods: {
    send() {
      //这里的开头用代理(我全局配置了axios)
      this.$axios.get("/randomPath/user/login?username=lili&password=123").then(
        function(promise) {
          console.log(promise.data);
        })
    }
  }
}
</script>
//vue.config.js文件内
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
    /* 解决跨域问题的配置 */
    devServer:{
      //配置代理
      proxy:{
      "/randomPath":{
        //参数为产生跨域的域名地址
        target:"http://localhost:8888",
        //设置true后,那么会在本地创建一个虚拟服务端(同域的),然后发送请求的数据并同时接收请求的数据,这样服务端和服务端进行数据交互就不会有跨域问题了
        changeOrigin:true,
        //路径重写
        pathRewrite:{
          //用来替换target中得到请求地址(前面为正则匹配)
          //也就是你在请求target中的地址时直接写成/randomPath即可
          '^/randomPath':''
        }
      }
    }
  }
})

Note: After the front-end solves the cross-domain problem, remember to restart the server. 

Backend services

Note: The backend port number is 8888 to provide services, and there is no cross-domain configuration.

@RestController
@RequestMapping("/user")
public class GetMsg {
    @GetMapping("/login")
    public String doLogin(@RequestParam("username") String username,@RequestParam("password") String password){
        System.out.println("请求进来了");
        return "你的名字为"+username+"你的密码为"+password;
    }
}

 

Guess you like

Origin blog.csdn.net/m0_60027772/article/details/126971505