08-Vue項目-API封裝

在src中創(chuàng)建文件夾api

config.js: http請求的基礎(chǔ)配置
http.js http請求接口配置

config.js

import axios from 'axios'

// 給所有axios請求設(shè)置基礎(chǔ)的域名
// axios.defaults.baseURL = 'http://localhost:3000'


//用axios.create可以創(chuàng)建axios的實例,允許不同實例有不同配置
const axios1 = axios.create({
    baseURL: 'http://localhost:3000',
    // 請求超時的時間
    timeout: 5000
}); 
// const axios2 = axios.create({
//     baseURL: 'http://www.test.com',
//     timeout: 5000
// });


//添加請求攔截器,會在發(fā)起請求之前執(zhí)行相應(yīng)的需求
axios1.interceptors.request.use(function (config) {
    // console.log('我是請求攔截器');
    config.headers.common['Authorization'] = 'Bearer ' + localStorage.getItem("token");
    // Do something before request is sent
    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });

// //添加響應(yīng)攔截器,會在返回數(shù)據(jù)后先執(zhí)行相應(yīng)的需求
axios1.interceptors.response.use(function (response) {
    console.log('我是響應(yīng)攔截器');
    // Do something with response data
    return response;
  }, function (error) {
    // Do something with response error
    console.log('error',error.status);

    return Promise.reject(error);
  });
export default axios1

http.js

 import axios1 from './config'

//查詢圖書
export function selectBook() {
    return axios1({
        url: '/book',
        method: 'get'
    })
}

// 添加圖書
export function addBook(data) {
    return axios1({
        url: '/book',
        method: 'post',
        data
    })
}

// 修改圖書
export function editBook(data) {
    return axios1({
        url: '/book',
        method: 'put',
        data
    })
}
//刪除圖書
export function delBook(params) {
    return axios({
        url: '/book',
        method: 'delete',
        params
    })
}

在業(yè)務(wù)需求中調(diào)用

import {selectBook} from '@/api/http';
......
//獲取初始化數(shù)據(jù)
getBookData() {
    selectBook()
    .then((res) => {
    this.book = res.data.list;
    })
    .catch((err)=>{
    console.log(err);
    })
},

也可以用async和await來優(yōu)化代碼

async getBookData() {
    try {
        let res = await selectBook();
        this.book = res.data.list;
    }catch(err){
        console.log(err);
    }
},

注意: main.js中不需要再引入axios, Vue的原型也不需要添加axios

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 在src中創(chuàng)建文件夾api config.js: http請求的基礎(chǔ)配置http.js http請求接口配置 co...
    懶懶貓閱讀 900評論 0 1
  • 在src中創(chuàng)建文件夾api config.js: http請求的基礎(chǔ)配置http.js http請求接口配置 co...
    民謠123閱讀 305評論 0 0
  • 在src中創(chuàng)建文件夾api config.js: http請求的基礎(chǔ)配置http.js http請求接口配置 co...
    alicemum閱讀 1,853評論 0 1
  • 前言 哈嘍大家周一好,今天的內(nèi)容比較多,主要就是包括:把前端頁面的展示頁給搭出來,然后調(diào)通接口API,可以添加數(shù)據(jù)...
    SAYLINING閱讀 1,381評論 0 2
  • 安裝nodejs 安裝git 下載vue-admin-template(前端) 建議本項目為可作為管理系統(tǒng)的基礎(chǔ)模...
    void_7bdf閱讀 741評論 0 0

友情鏈接更多精彩內(nèi)容