Notes: Simple use of axios

concept

Axios is a promise-based HTTP library that can be used in browsers and node.js. Ajax similar to jq
axios is a library
that has been packaged ajax does not support the advantages of jsonp

  • Create XML HttpRequests from the browser
  • Create http request from node.js
  • Support Promise API
  • Intercept request and response
  • Convert request data and response data
  • Cancel request
  • Automatically convert JSON data
  • The client supports defense against XSRF (cross-site request forgery)

Mount to Vue instance

  • You can mount axios directly on Vue, so that each page can be used directly without importing
Vue.prototype.$http = axios
// 直接用this.$http就相当于axios

Return data

config // 请求的时候附带的配置参数,method,url之类
data // 后端返回的数据
headers // 请求头里面包含发送给后端的格式application/json; charset=UTF -8
request // ajax请求
status // 返回的状态码
statusText // 返回的状态文字

Steps for usage

  • installation
npm install axios --save
  • Introduce
import axios from 'axios'
  • Can be introduced in the main.js file
  • It can also be introduced on the component page that needs to be used
  • After mounting to the prototype of the Vue instance, there is no need to introduce it
  • Specify configuration information
axios.请求方式('requestPath',{
    
    data},{
    
     配置信息 })
  • Request header

json

axios.请求方式('requestPath',{
    
    data},{
    
     headers:{
    
     "Content-Type":"application/json" }})

String pattern

axios.请求方式('requestPath',{
    
    data},{
    
    headers:{
    
     "Content-type":"x-www-from-urlencoded" }})

Form

axios.请求方式('requestPath',{
    
    data},{
    
    headers:{
    
     "Content-type":"multipart/form-data" }})
  • get request
axios.get('requestPath')
.then(res => {
    
      })
  • Pass parameters
axios.get('requestPath',{
    
    
	params:{
    
    
		key=value
	}
})
  • post request
axios.post('requestPath')
.then(res => {
    
      })
  • Passing parameters is the same as get request

Precautions

  • When axios uses post to send data, the default is to directly convert the passed parameters into json and put it in the request body and submit it to the backend. In other words, our Content-Type has become application/json;charset=utf-8
    , which is the default content-type of axios request header. But the actual requirement of our back-end'Content-Type':
    'application/x-www-form-urlencoded' is more common. This is not in line with us.
  • In the HTTP protocol message header, Content-Type is used to indicate the media type information in the request and response. It is used to tell the server how to process the requested data, and tell the client (usually a browser) how to parse the response data, such as displaying pictures, analyzing and displaying htm| etc.

Solution

  • Introduce qs library
import qs from 'qs'
  • Not every post value needs to be introduced, specifically communicate with the background
const 参数集合 = {
    
     key=value,key=value }
axios.post('requestPath',qs.stringify(参数集合))
  • Low-level writing
axios({
    
    
	url:'requestPath',
	paramsL:{
    
     参数 },
	methodes:'请求方式',
	// ...其他配置项
})
  • Set public request address
  • The address used during development and when the project is officially launched is different, which can help us change the address easily.
  • In fact, the address we requested is divided into two parts: the domain name address and the interface address. Set the public domain name address directly when requesting the interface address.

format

axios.defaults.baseURL = '域名地址'
  • Write like this when requesting
axios.get('接口地址')

Timeout disconnect request

  • Ajax is always requesting, only when the backend sends data to the front end, ajsx will end, which will cause a waste of bandwidth. You can set a timeout for ajax to disconnect
  • For example, if there is no return data after waiting for 5s, disconnect the connection
  • Set up
axios.defauls.timeout = 毫秒数

Request to carry information

token

  • Token is the token returned when logging in. If the backend asks the data to be requested on other pages with a token, the
    general user judges whether the user logs in is judged based on the token. Generally, this token is stored in the session,
    as long as the toke is written in the request header. Know we are logged in
  • Save the sessionkey when logging in, and then bring this sessionkey when requesting other interfaces. The sessionkey represents the user’s identity.
  • We bring this sessionkey when requesting data, so the backend knows who is requesting the data now. There are some special circumstances. When logging in, the backend will set the cookie
    token locally, and he will judge whether the user is logged in based on the value token in the cookie.
axios.defaults.headers.common['sessionKey']=登陆时后端返回的sessionKey
  • If you need to verify every time you request the interface, just add this, no need to verify then don’t add
axios.defaults.headers.common['token'] = localStorage['token']
  • Generally used for login and registration

After the login is successful, the background will return a sessionkey to
save it
. When requesting other interfaces later, bring this sessionkey to
set the carrying information

axios.defaults.headers.common['token'] = 保存在本地的token
// 中括号里的token适合后台商量好的名字,不一定是token

Interceptor

  • The page sends http requests. In many cases, we need to perform specific processing on the request and its response. If the number of requests is very large, processing each request separately will become very troublesome, and the elegance of the program will be greatly reduced. Fortunately, the powerful axios provides developers with such an API: interceptor.
  • You can do some special processing when requesting and corresponding
  • Generally used for data processing, or to give the entire page a mask layer while waiting

Example:
serialize data rows when requesting post

axios.interceptors.request.use(function(config) {
    
    
	if(config.method == 'post') {
    
    
		config.data = qs.stringify(config.data) 
	}
	return config
},function(error) {
    
    
	return Promise.reject(error)
})

Response interceptor

axios.interceptors.response.use

Guess you like

Origin blog.csdn.net/m0_47883103/article/details/108473043