The use of Vue axios and cross-domain issues

  1. Features of axios

Features

  • XMLHttpRequests can be sent in the browser

  • Can send http request in node.js

  • Support Promise API

  • Can intercept requests and responses

  • Can convert request and response data

  • Client supports prevention CSRF

  • Provides some interfaces for concurrent requests (important, facilitates many operations)

  • Automatically convert to JSON data format

  • axios handles errors: just use catch()

Supports multiple request methods:

axios(config)

axios.request(config)

axios.get(url[, config])

axios.delete(url[, config])

axios.head(url[, config])

axios.post(url[, data[, config]])

axios.put(url[, data[, config]])

axios.patch(url[, data[, config]])

Summary of get request method:


A: 无参数
        axios.get(url).then(res=>console.log(res).catch(error=>conosle.log(error))
 B: 有参数
        axios({
            url: 'http://xxx',
            method: 'get' //默认就是get,这个可以省略,
            params: {//URL查询对象
                key: value
            }
        })

Post request method summary


//对于post请求可以统一设置一个请求头,后面所有post请求就可以不用单独设置请求头了
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

 // 具体语法
 let params = new URLSearchParams()//得到params对象,用来接收请求参数

// params.append(key,value) //请求参数写成键值对key就是参数名,value就是参数值

params.append('a',1)
params.append('b',2)

axios({
    url: 'http://localhost/post.php',
    method: 'post',
    data: params,//将请求参数写入data;
      headers: {  //单个请求设置请求头
       'Content-Type': "application/x-www-form-urlencoded"
    }
})
.then(res => {
    console.log( res )
})
.catch( error => {
    if( error ){
    throw error
}
})

Background: Because only get and post methods can be used to request data in axios, there is no provisionjsonpWait for cross-domain data access

Since direct cross-domain access using axios is not feasible, we need to configure a proxy.

The reason why the proxy can solve it: Because there is a cross-domain problem when the client requests data from the server, and the server< a i=3> and the server can request data from each other, and there is no concept of cross-domain (if the server does not set permissions to prohibit cross-domain)

In other words, we can configure a proxy server to request data from another server, and then return the requested data to our proxy server. The proxy server then returns the data to our client, so that we can achieve Access data across domains.

  1. ConfigureBaseUrl

In main.js


import { createApp} from 'vue'
import axios from 'axios'
import App from './App.vue'
import router from "@/router"

axios.defaults.baseURL="/api" //
createApp(App).use(router).mount('#app')
  1. Placement proxy (Solution straddle)

It is configured in the vue.config.js file, and some is configured in the index.js file under the config folder.


 // 配置跨域
    proxy: {
      "/api": {
        target: "http://192.168.0.139:8801",//需代理的后端接口
        secure: false,//开启代理:在本地会创建一个虚拟服务端,然后发送请求的数据,并同时接收请求
        changeOrigin: true,
        pathRewrite: {
          "^/api": "/",//重写匹配的字段。把/api 转为 /
        }
      }
    },
  1. Where axios is specifically used, just modify the url as follows:


 axios.get("/movie/top250").then((res) => {
                  res = res.data
                  if (res.errno === ERR_OK) {
                     this.themeList=res.data;
                  }
                }).catch((error) => {
                  console.warn(error)
                })

axios package


import axios from "axios"
axios.defaults.timeout = 10000;
//对于post请求可以统一设置一个请求头,后面所有post请求就可以不用单独设置请求头了
axios.defaults.headers.post['Content-Type'] = 'application/json';

export function post(url,data){
    return new Promise((resolve,reject)=>{
        axios({
            url:url,
            method:"post",
            data:data,
        }).then(res=>{
            resolve(res.data)
        }).catch(err=>{reject(err.data)})
    })
}

export function get(url,params){
    return new Promise((resolve,reject)=>{
        axios({
            url:url,
            methods:"GET",
            params:params
        }).then(res=>{
            resolve(res.data)
        }).catch(err=>{reject(err.data)})
    })
}

The use of axios call encapsulation


import {post} from './http'
export const save =data=>post("questionnaire/save",data)

How to use axios interceptor?

Interceptors are generally divided into two types: request interceptors and response interceptors, which intercept requests or responses before they are processed by then or catch. .

  1. The request interceptor performs necessary operations before sending the request, such as adding a unified cookie, verifying the request body, setting request headers, etc., which is equivalent to an encapsulation of the same operations in each interface;

  1. Response interceptor In the same way, the response interceptor also has the same function, except that after the request is responded to, some processing of the response body is usually unified processing of data, etc., and it is also often used to determine login failure, etc.

For example, if some websites do not operate for a certain period of time, they will log out and let you log in again. Of course, this function can be completed without an interceptor, but it will be very troublesome and the code will generate a lot of duplication, so we need to use interception. device.

Application scenarios

1: Each request carries parameters, such as token, timestamp, etc.

2: Judge the returned status, such as whether the token has expired

request interception


// 添加请求拦截器--代码实现案例:仅供参考
axios.interceptors.request.use(function (config) {
  // 在发送请求之前做些什么, 如果vuex里有token携带在请求头中
  if (store.state.token.length > 0 && config.headers.Authorization === undefined) {
    // 发起请求之前, 把token携带在请求头上(表明自己身份)
    config.headers.Authorization = 'Bearer ' + store.state.token
  }
 // 配置token
     // config.headers.AuthorizationToken = localStorage.getItem('AuthorizationToken')
  return config
},function (error) {
  // 对请求错误做些什么
    return Promise.reject(error)
})

response interception


// 添加响应拦截器--代码实现案例:仅供参考
axios.interceptors.response.use(function (response) { // 当状态码为2xx/3xx开头的进这里
    //  想根据业务需要,对响应结果预先处理的,都放在这里
    return response
}, (error)=> { // 响应状态码4xx/5xx进这里
    // 对响应错误做点什么
   if (error.response.status === 401) { // 身份过期/token无效
    //  1.清空vuex的token 
    store.commit('setToken', '')
    store.commit('setRefreshToken', '')
    // 2. 清空本地token 
    localStorage.removeItem('token')
    localStorage.removeItem('refresh_token')
    //  跳转到登录页面登录
    router.push({
      path: '/login'
    })
  }     
    return Promise.reject(error)
})
//所有api接口里以后暂时不用自己携带Headers+Token了,简略代码,统一管理

what is jsonp

In front-end development, one of our common network request methods is JSONP

The main reason for using JSONP is often tosolve the problem of cross-domain access.

What is the principle of JSONP?

The core of JSONP lies in passing<script> The src of the tag helps us request data.

The reason is that when our project is deployed on thedomain1.com server, it cannot be accessed directly The data on domain2.com server will cause cross-domain problems.

At this time, we use the src of the<script> tag to help us request the data from the server and treat the data as a javascript function to execute, and pass in the json we need during the execution.

Therefore, the core of encapsulating jsonp lies in the name when we listen to the jsonp on the window and call back.

What is cross-domain?

Cross-domain occurs when the port, protocol, and domain name of the backend interface URL and the page URL are different in one or more ways.

Proxy is also called a network proxy

What is an agent?

In layman's terms, it is a middleman.

Officially, it is a special network service that allows a client to make an indirect connection with another network terminal (usually a server) through this service. Some network devices such as gateways and routers have network proxy functions. It is generally believed that proxy services are helpful in ensuring the privacy or security of network terminals and preventing servers from being attacked.

Guess you like

Origin blog.csdn.net/ili_ii/article/details/128805765