axios基本配置 使用方法vue
import axios from 'axios' // 建立axios實例 const service = axios.create({ baseURL: process.env.BASE_API, // node環境的不一樣,對應不一樣的baseURL timeout: 5000, // 請求的超時時間 //設置默認請求頭,使post請求發送的是formdata格式數據// axios的header默認的Content-Type好像是'application/json;charset=UTF-8',個人項目都是用json格式傳輸,若是須要更改的話,能夠用這種方式修改 // headers: { // "Content-Type": "application/x-www-form-urlencoded" // }, withCredentials: true // 容許攜帶cookie })
封裝get和post方法node
import axios from 'axios'; const serverconfig = require('../../static/serverconfig.json') // 這個json文件中配置接口根目錄地址 class Axios{ getUrl(url){ return `${serverconfig.ApiUrl}${url}`; // 獲取完整的接口地址 }; // post 請求 postServer(opt) { const _axios = axios.create({ timeout: 10000 }); let data = {}; if (opt.data) { data = opt.data; } _axios.post(opt.url, data).then((response) => { console.log(response); if(response.data.status === 'error'){ // 這裏用layer彈層插件 layer.open({ content: 'error:' + response.data.hotelInfo ,skin: 'msg' ,time: 2 //2秒後自動關閉 }); if (opt.onFailed) { opt.onFailed(response); } return; } if (opt.onSuccess) { opt.onSuccess(response); } }).catch(error => { if (opt.onFailed) { opt.onFailed(error); } if (!error.response.data.success) { alert(error.response.data.error.message); // return; } }); } // get 請求 getServer(opt) { const _axios = axios.create({ timeout:10000 }); let data = {}; if (opt.data) { data = opt.data; } _axios.get(opt.url, {params: data}).then((response) => { if (opt.onSuccess) { opt.onSuccess(response); } }).catch(error => { if (opt.onFailed) { opt.onFailed(error); } }); } setData(opt) { let data = {}; if (opt.data) { data = opt.data; } return data; } } export default Axios;
封裝接口ios
hotel.service.js
import Axios from './axios.service' const AxiosMethods = new Axios(); sendQueryServer(opt){ const data = AxiosMethods .setData(opt); const url = AxiosMethods .getUrl('/Home/Query'); AxiosMethods .postServer({url, data, onSuccess: opt.onSuccess, onFailed: opt.onFailed}); } }
頁面調用query.vuejson
import HotelServer from "@/service/hotel.service" const hotelServer = new HotelServer(); methods:{ _sendQueryServer() { const loadingIndex = this.loadingShow() hotelServer.sendQueryServer({ onSuccess: (res) => { layer.close(loadingIndex) console.log(res) }, onFailed: (res) => { layer.close(loadingIndex) } }) }