vue3.0 axios请求封装(vue2.0也适合)

1.引入axios

npm install axios

2.src下面创建http文件夹(下图)
在这里插入图片描述
api.js

import axios from 'axios'
var $http = axios.create({
    
    
    baseURL: 'https://wwww.baidu.com'//服务器地址
});
// 添加请求拦截器
$http.interceptors.request.use(function (config) {
    
    
    // 在发送请求之前做些什么
    config.headers['Authorization'] = 'Bear ' + '123456'//按需求写入token
    return config;
}, function (error) {
    
    
    // 对请求错误做些什么
    return Promise.reject(error);
});

// 添加响应拦截器
$http.interceptors.response.use(function (response) {
    
    
    // 对响应数据做点什么
    let data = response.data
    return data;
}, function (error) {
    
    
    // 对响应错误做点什么
    return Promise.reject(error);
});

export default $http

index.js

import axios from './api'
let api = {
    
    }
// 登陆
api.login = function (data) {
    
    
    return axios({
    
    
        url: '/login',
        method: 'POST',
        data: data
    })
}
export default api

页面引用

import api from '@/http/index.js';

setup中调用

    let login = () => {
    
    
      let data = {
    
    
        username: '小三',
        password: '123456789'
      };
      api.login(data).then((res) => {
    
    
        if (res.error_code === 'Success') {
    
    
          console.log(res.data);
        }
      });
    };
     return {
    
    
       login
    };

猜你喜欢

转载自blog.csdn.net/weixin_44816309/article/details/114968440