Vue encapsulates the get and post requests of Axios

Axios is used a lot in vue projects, it is inconvenient to write it every time, especially the config configuration item is public, it can be completely encapsulated, so that you can directly CV when you use it next time! After all, CV Dafa incense!

  1. Encapsulate Axios basic configuration
    Create a request.is file, the content is as follows, I put the explanatory text in the comment.
import axios from 'axios'


export function request(config) {
    
    
  // 1.创建axios的实例
  const instance = axios.create({
    
    
    // 设置基础的url配置项,这样接口处的url前面就不用写url:'http://127.0.0.1:8000/api/home',直接写成 url:'/api/home', 就可以了
    baseURL: 'http://127.0.0.1:8000/', 
    //设置请求超时时间
    timeout: 5000 
  })

  // 2.axios的拦截器,用不到的可以忽略这节
  // 2.1.请求拦截的作用
  instance.interceptors.request.use(config => {
    
    
    return config
  }, err => {
    
    
    console.log('请求拦截err: '+err);
  })

  // 2.2.响应拦截
  instance.interceptors.response.use(res => {
    
    
    return res.data
  }, err => {
    
    
        console.log('响应拦截err: '+err);
  })

  // 3.发送真正的网络请求
  return instance(config)
}

  1. Encapsulate network requests.
    We can put all relevant network requests in a js, so that it is easy to find when using and modifying. The get request is relatively simple, and the post request requires different settings according to the transmission type.
    Now let’s talk about the common data format (content-type) of post requests.
    Content-Type: application/json : The data in the request body will be sent to the backend in the form of json strings . This is the default request data type of axios. We only need to pass the parameter serialized json string without extra configuration.
    Content-Type: application/x-www-form-urlencoded : the data in the request body will be sent to the backend in the form of a normal form (key-value pair)
    Content-Type: multipart/form-data : it will send the data in the request body Processed as a message, with tags as the unit, separated by separators. You can upload key-value pairs or files.
    Create a network.js file with the following content:
// 导入封装好的Axios
import {
    
    request} from './request' //注意request.js的相对路径问题

//1. get请求---获取首页的多个数据
export function getHomeMultidata() {
    
    
  return request({
    
    
    url:'/api/home',
    method:'get',
    // 可以带参数也可以不带参数
    // params: {
    
    
    //     userName: 'Lan',
    //     password: '123'
    // }
  })
}
// 2.1 post请求---传输json数据时,获取电视剧多个数据
export function getTvshowMultidata() {
    
    
  return request({
    
    
    url:'/api/Tvshow',
     headers: {
    
    
      'Content-Type': 'application/json'
    },
    method:'post',
    data: {
    
    
        userName: 'Lan',
        password: '123'
     }
  })
}

//2.2 post请求---传输文件流,表单Form Data 数据时
export function getMovieMultidata() {
    
    
  return request({
    
    
    url:'/api/Movie',
    headers: {
    
    
    'Content-Type': 'multipart/form-data';
    },
    method:'post',
    data: {
    
    
        userName: 'Lan',
        password: '123'
     }
  })
}


  1. Use
    in vue: Import the methods that need to be used in network.js in the script tag on demand
  import {
    
    getHomeMultidata} from "network/home/network"; //导入js,路径自己根据文件位置设置

In the method, call the function according to the format of the promise

created() {
    
    
      // 在方法中调用函数即可
        getHomeMultidata().then(
          res => {
    
    
          // 此处res 为返回的数据,将返回的数据进行处理显示
            this.banners = res.homedata.slice(0,5)
            this.newestData = res.homedata.slice(5,12)
            
        ).catch(
          err => {
    
    
            console.log(err)
          }
        );
    },

The method of using other network request methods in network is the same as above.

Guess you like

Origin blog.csdn.net/weixin_41897122/article/details/114180364