参考文档:https://www.cnblogs.com/deng-jie/p/12420873.html
https://juejin.cn/post/6844903652881072141
创建一个http.js文件
import axios from "axios" import { Toast } from 'vant'; // 环境的切换 if (process.env.NODE_ENV == 'development') { axios.defaults.baseURL = 'https://uniapp-toutiao.herokuapp.com/'; } else if (process.env.NODE_ENV == 'debug') { axios.defaults.baseURL = 'https://uniapp-toutiao.herokuapp.com/'; } else if (process.env.NODE_ENV == 'production') { axios.defaults.baseURL = 'https://uniapp-toutiao.herokuapp.com/'; } // 请求超时时间 axios.defaults.timeout = 2000 //post请求头 application/json;charset=UTF-8 axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'; // 请求拦截器 axios.interceptors.request.use(function (config) { // 请求的时候加个toke,存在就加上 let token = window.localStorage.getItem("token") if (token) { config.headers.token = token //也可以这种写法 // config.headers['token'] = token; } Toast.loading({ message: '请求中...', forbidClick: true, duration: 0, }); return config; }, function (error) { // Do something with request error Toast.fail('请求失败!'); return Promise.reject(error); }); // 响应拦截器 axios.interceptors.response.use(function (response) { //判断下相应过来的状态码,这里根据后端怎么写响应码有关 Toast.clear(); return response; }, function (error) { //判断响应错误码 // if (error.response.status) { // switch (error.response.status) { // case 401: // console.log(401) // break // case 403: // console.log(403) // break // case 404: // console.log(404) // break // default: // Toast({ // message: '默认响应错误码', // duration: 1500, // forbidClick: true // }); // } // } Toast.fail("服务器连接失败"); return Promise.reject(error); }); //通用方法 export const GET = (url, params) => { return axios.get(url, params) } export const POST = (url, params) => { return axios.post(url, { params: params }).then( res => { console.log(res.data) } ) }
在main.js中引入
import Vue from 'vue' import App from './App.vue' import router from './router' import store from './store' import Vant from 'vant'; import 'vant/lib/index.css'; import "./http" import { GET, POST } from './http'; Vue.prototype.postRequest = POST Vue.prototype.getRequest = GET Vue.use(Vant); Vue.config.productionTip = false new Vue({ router, store, render: h => h(App) }).$mount('#app')
使用案例
<template> <div> <van-button @click="jay" type="primary">主要按钮</van-button> </div> </template> <script> export default { data() { return { url: "https://uniapp-toutiao.herokuapp.com/api/profiles/home_tab_list", url2:"api/profiles/home_tab_list" }; }, methods: { jay() { this.getRequest(this.url2).then( res=>{ console.log(res.data); } ) }, }, }; </script> <style lang="scss" scoped> </style>