Secondary packaging of axios and solving cross-domain problems

1. Why is axios packaged twice?

We need to use request interceptor and response interceptor when requesting data;
request interceptor: can process some business before sending the request
Response interceptor: when the server data is returned, it can process some things

cnpm install --save axiosInstall axios using

insert image description here
Usually, the project has an api folder (the folder for secondary packaging of axios)
1. Create an api folder
2. Create request.js under the api folder (used to write the code for secondary packaging of axios)
insert image description here
3 .Write the code of axios secondary packaging in request.js

// 对于axios进行二次封装
import axios from 'axios'

// 1.利用axios对象的方法create,去创建一个axiox实例
// 2.request就是axios,只不过稍微配置一下

const requests = axios.request({
    
    
  // 配置对象
  // 基础路径,发送请求的时候,路径当中会出现api
  baseURL: '/api',
  // 代表请求超时的时间5s
  timeout: 5000
})

// 请求拦截器:在发送请求之前,请求拦截器可以检测到,可以在请求发出去之前做一些事情
requests.interceptors.request.use((config) => {
    
    
  // config:配置对象,对象里面有一个属性很重要,headers请求头
  return config
})

// 响应拦截器:当服务器返回数据以后,可以处理一些事情
requests.interceptors.response.use((res)=>{
    
    
  // 成功的回调函数:服务器响应数据回来以后,响应拦截器可以检测到,可以做一些事情
  return res.data;
},(error)=>{
    
    
  // 响应失败的回调函数
  return Promise.reject(new Error('faile'))
})

// 对外暴露
export default requests

4. Unified management of api (there are many requested interfaces, which require unified management)

1. Create a new index.js in the api folder for the management interface
2. Write code in index.js

// 当前模块作用:用于所有的API进行统一的管理
import requests from './request'

// 三级联动接口
// /api/product/getBaseCategoryList   get请求 无参数

export const reqCategoryList = () => {
    
    
  // 发请求:axios发送请求返回结果是Promise对象
  return requests({
    
     url: '/product/getBaseCategoryList', method: 'get' })
}

cross-domain issues

What is cross-domain: requests with different protocols, domain names, and port numbers are called cross-domain
Example: http://localhost:8000/#/home — the local server of the front-end project
http://gmall-h5-api.atguigu. cn — the backend server that calls the data.
If you directly call the backend server data, 404 will appear

There are three ways to solve cross-domain problems: JSONP, CROS, and proxy server configuration.
Here we use proxy server configuration to solve the problem. Configure the following code in vue.config.js

insert image description here

Guess you like

Origin blog.csdn.net/m0_66504310/article/details/128566588