Summary of several ways of front-end request interface

As a front-end engineer, it is inevitable to request the back-end interface to obtain data, and it is also a necessary skill for front-end personnel to master. But you only use one request method for a period of time, and suddenly you change to another method that may not be able to be realized immediately. For this reason, I summarized the front-end request API method for future reference.

One, vue-resource

Advantages: small size, support mainstream browsers, support Promise API and URI Templates, support interceptors.

installation

    $ yarn add vue-resource
    $ npm install vue-resource

use

	/*引入Vue框架*/
	import Vue from 'vue'
	/*引入资源请求插件*/
	import VueResource from 'vue-resource'
	
	/*使用VueResource插件*/
	Vue.use(VueResource)

common:

this.$http.get().then()
this.$http.post().then()
this.$http.jsonp().then()

Learning link: vue-resource

Two, axios

After vue2.0, vue-resource is no longer updated, but axios is recommended. Promise-based HTTP request client, which can be used in browser and Node.js at the same time.

advantage:

(1) Send XMLHttpRequests request in the browser
(2) Send http request in node.js
(3) Support Promise API
(4) Intercept request and response
(5) Convert request and response data
(6) Cancel request
(7) Automatically convert to JSON data
(8) The client supports the protection of security from CSRF/XSRF attacks

Use directly alone:

  • get method

    axios.get().then().catch()

Note: Passing parameters in the get method can directly follow the url or pass through the param object

  • post method

    axios.post().then().catch()

Note: Passing parameters in post mode must be passed by object

In actual development, axios will be encapsulated for easy invocation, and interceptors are used to control the request status

Encapsulate axios request:

Create an api file, encapsulate a request.js file in the current directory, and configure the interception information of the request response

/**
 * @file axios请求封装
 */
import axios from 'axios'
import store from '../store/common'
import router from '../router/common'
import {
    
     Toast } from 'vant'

const Axios = axios.create({
    
    })

// 响应时间
Axios.defaults.timeout = 10000
// `withCredentails`选项表明了是否是跨域请求
Axios.defaults.withCredentials = true
// 设置默认请求头
Axios.defaults.headers = {
    
    
  'X-Requested-With': 'XMLHttpRequest',
  'Content-Type': 'application/json; charset=UTF-8'
}

// 添加请求拦截器
Axios.interceptors.request.use(
  config => {
    
    
    // loadingInstance = Loading.service({
    
    
    //   fullscreen: true
    // });
    // 获取token
    let token = store.getters.getToken
    if (token) {
    
    
      // 判断是否存在token,如果存在的话,则每个http header都加上token
      config.headers.Authorization = token
    }
    return config
  },
  error => {
    
    
    return Promise.reject(error)
  }
)

// 添加返回拦截器
Axios.interceptors.response.use(
  response => {
    
    
    if (
      typeof response != 'undefined' &&
      (response.data.code == 1001 ||
        response.data.code == 0 ||
        response.data.code == 1000 ||
        response.data.code == 1100 ||
        response.data.code == 1200)
    ) {
    
    
      return response.data
    } else if (response.data.code == 20008) {
    
    
      // 交班后选机器号
      checkCode('当前无人当班,请选择机器号')
      router.replace('/center/machine')
      return response.data
    } else if (response.data.code == 1006) {
    
    
      // Token过期
      checkCode('登录过期,请重新登录')
      return response.data
    } else if (typeof response != 'undefined' && response.data.msg) {
    
    
      checkCode(response.data.msg)
      return response.data
    } else {
    
    
      checkCode('操作失败,请重试')
    }
    return ''
  },
  error => {
    
    
    if (error && error.response) {
    
    
      switch (error.response.status) {
    
    
        case 400:
          error.message = '请求错误'
          break
          ...
        default:
      }
    } else {
    
    
      error.message = '无法连接服务器'
    }
    // 对返回的错误处理
    return Promise.reject(error)
  }
)

// 请求失败错误信息提示
function checkCode(message) {
    
    
  // 关闭loading
  // loadingInstance.close();
  // 弹出错误信息
  Toast(message)
}
export default Axios

Create an index.js file unified writing request interface, as shown in the figure below:
Insert picture description here
Globally expose the request interface api. In the vue.config.js file, configure chainwebpack and set the alias of the api to use the api interface globally.

chainWebpack: config => {
    
    
    config.resolve.alias
      .set('api', path.resolve('./src/api/index.js'))
    config.plugin('provide').use(webpack.ProvidePlugin, [
      {
    
    
        api: 'api'
      }
    ])
  }

Interface request: await api.getName (the corresponding interface name under index.js) can be used directly

await api.pageSalesOrderProsDetailData(this.formDate).then(response => {
    
    
        if (response.data) {
    
    
          this.goodsList = this.goodsList.concat(response.data.content)
          this.totalPages = response.data.totalPages
          if (response.data.content.length < this.formDate.pageCount) {
    
    
            this.$store.commit('SET_ALL_LOADING', true)
          }
        }
        this.$store.commit('SET_SALES_RANK_MSG', this.goodsList)
      })

Axios packaging and API interface management in vue

Three, ajax

Ajax encapsulated using Jquery

$.ajax({
    
    
    url:"http://www.microsoft.com", //请求的url地址
    dataType:"json", //返回格式为json
    async:true,//请求是否异步,默认为异步,这也是ajax重要特性
    data:{
    
    "id":"value"}, //参数值
    type:"GET", //请求方式
    beforeSend:function(){
    
    
        //请求前的处理
    },
    success:function(req){
    
    
        //请求成功时处理
    },
    complete:function(){
    
    
        //请求完成的处理
    },
    error:function(){
    
    
        //请求出错处理
    }
});

Parameter explanation:

$.ajax({
    
    
  url:"   ",                 //请求的地址
  type:"   ",              //请求方式两种“get”或者“post”,默认为“get”
  timeout:             //设置请求超时时间(毫秒。
  async:               //是否异步,默认设置为true,所有请求均为异步请求。如果需要发送同步请求,请将此选项设置为false。注意,同步请求将锁住浏览器,用户其他操作必须等待请求完成才可以执行。
  cache:             //默认为true(当dataType为script时,默认为false),设置为false将不会从浏览器缓存中加载请求信息。
  data:               //要求为Object或String类型的参数,发送到服务器的数据。get请求中将附加在url后
  dataType:      //预期服务器返回的数据类型。可用的类型如下:
				xml:返回XML文档,可用JQuery处理。
				html:返回纯文本HTML信息;包含的script标签会在插入DOM时执行。
				json:返回JSON数据。
				jsonp:JSONP格式。使用SONP形式调用函数
  beforeSend:   //发送请求前可以修改XMLHttpRequest对象的函数,例如添加自定义HTTP头
  complete:        //请求完成后调用的回调函数(请求成功或失败时均调用)。
  error:        //请求失败时被调用的函数。该函数有3个参数,即XMLHttpRequest对象、错误信息、捕获的错误对象(可选)
})

Four, WebSocket

Reason for emergence: The
most common interaction mode between front-end and back-end is that the front-end sends data requests and displays the data on the page after getting the data from the back-end. If the front end does not perform operations, the back end cannot actively push data to the front end, which is also a defect of the http protocol. Therefore, a new communication protocol came into being—websocket. Its biggest feature is that the server can actively push messages to the client, and the client can also actively send messages to the server, realizing true equality.

Usage scenarios: use in scenarios where the
latest data is returned without request, such as financial stock data graphs, instant order information, weather, whether the token is expired, etc.

Note: Vue needs to pay attention to the following points when using websocket:

(1) First, it is necessary to determine whether the browser supports websocket.
Insert picture description here
(2) Connect the websocket when the component is loaded, and disconnect the websocket when the component is destroyed
(3) The back-end interface needs to introduce the socket module, otherwise the connection cannot be realized

for example:

<template>
    <div>
        <button @click="send">发消息</button>
    </div>
</template>
<script>
export default {
    
    
    data () {
    
    
        return {
    
    
            path:"test",
            socket:""
        }
    },
    mounted () {
    
    
        // 初始化
        this.init()
    },
    methods: {
    
    
        init: function () {
    
    
            if(typeof(WebSocket) === "undefined"){
    
    
                alert("您的浏览器不支持socket")
            }else{
    
    
                // 实例化socket
                this.socket = new WebSocket(this.path)
                // 监听socket连接
                this.socket.onopen = this.open
                // 监听socket错误信息
                this.socket.onerror = this.error
                // 监听socket消息
                this.socket.onmessage = this.getMessage
            }
        },
        open: function () {
    
    
            console.log("socket连接成功")
        },
        error: function () {
    
    
            console.log("连接错误")
        },
        getMessage: function (msg) {
    
    
            console.log(msg.data)
        },
        send: function () {
    
    
            this.socket.send(params)
        },
        close: function () {
    
    
            console.log("socket已经关闭")
        }
    },
    destroyed () {
    
    
        // 销毁监听
        this.socket.onclose = this.close
    }
}
</script>

Guess you like

Origin blog.csdn.net/Smell_rookie/article/details/100052286