Project network request module package-simple and practical

During the development of the vue project, the page request data will initiate a request to the server, and the user will initiate a request when interacting. In order to manage these requests in a unified manner, we encapsulate them into an independent method; and introduce them where needed; this is very convenient Maintenance of the project in the future...
axios package

 axios库,它是基于promise的http库,可运行在浏览器端和node.js中。他有很多优秀的特性,
 例如拦截请求和响应、取消请求、转换json、客户端防御XSRF等

installation:npm i axios --save

1. Create a new api folder, generate axios.js and method.js;

Insert picture description here
axios.js is used to create axios instance, method.js is used to define request to method

2. The axios.js code is as follows

import axios from 'axios';

const service = axios.create({
    
    
  baseURL: '/api',
  timeout: 6600,  //超时时间
});
  1. Request interception and corresponding interception

// 添加请求拦截器
service.interceptors.request.use(config => {
    
    
  // 在发送请求之前做些什么
  if (localStorage.getItem('token')) {
    
    
	//请求头设置token或作者
  	//config.headers.token = 'Bearer ' + localStorage.getItem('token')
    config.headers.Authorization = 'Bearer ' + localStorage.getItem('token')
  }
  return config
}, error =>
  // 对请求错误做些什么
  Promise.reject(error),
);

// response interceptor
service.interceptors.response.use(
  response => {
    
    
	return response
  },
  error => {
    
    
    console.log('err' + error) // for debug
    return Promise.reject(error)
  }
)
//抛出实例对象
export default service

method.js code

import request from './request'

export function login(data) {
    
    
  return request({
    
    
    url: '/vue-element-admin/user/login',
    method: 'post',
    data
  })
}

Guess you like

Origin blog.csdn.net/weixin_51198863/article/details/112852984